Cross-Site Request Forgery (CSRF) Protection

class microdot.csrf.CSRF(app=None, cors=None, protect_all=True, allow_subdomains=False)

CSRF protection for Microdot routes.

Parameters:
  • app – The application instance.

  • cors – The CORS instance that defines the origins that are trusted by the application. This is used to validate requests from older browsers that do not send the Sec-Fetch-Site header.

  • protect_all – If True, all state changing routes are protected by default, with the exception of routes that are decorated with the exempt decorator. If False, only routes decorated with the protect decorator are protected. The default is True.

  • allow_subdomains – If True, requests from subdomains of the application domain are trusted. The default is False.

CSRF protection is implemented by checking the Sec-Fetch-Site sent by browsers. When the cors argument is provided, requests from older browsers that do not support the Sec-Fetch-Site header are validated by checking the Origin header.

initialize(app, cors=None)

Initialize the CSRF class.

Parameters:
  • app – The application instance.

  • cors – The CORS instance that defines the origins that are trusted by the application. This is used to validate requests from older browsers that do not send the Sec-Fetch-Site header.

exempt(f)

Decorator to exempt a route from CSRF protection.

This decorator must be added immediately after the route decorator to disable CSRF protection on the route. Example:

@app.post('/submit')
@csrf.exempt
# add additional decorators here
def submit(request):
    # ...
protect(f)

Decorator to protect a route against CSRF attacks.

This is useful when it is necessary to protect a request that uses one of the safe methods that are not supposed to make state changes. The decorator must be added immediately after the route decorator to disable CSRF protection on the route. Example:

@app.get('/data')
@csrf.force
# add additional decorators here
def get_data(request):
    # ...