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
CORSinstance that defines the origins that are trusted by the application. This is used to validate requests from older browsers that do not send theSec-Fetch-Siteheader.protect_all – If
True, all state changing routes are protected by default, with the exception of routes that are decorated with theexemptdecorator. IfFalse, only routes decorated with theprotectdecorator are protected. The default isTrue.allow_subdomains – If
True, requests from subdomains of the application domain are trusted. The default isFalse.
CSRF protection is implemented by checking the
Sec-Fetch-Sitesent by browsers. When thecorsargument is provided, requests from older browsers that do not support theSec-Fetch-Siteheader are validated by checking theOriginheader.- initialize(app, cors=None)¶
Initialize the CSRF class.
- Parameters:
app – The application instance.
cors – The
CORSinstance that defines the origins that are trusted by the application. This is used to validate requests from older browsers that do not send theSec-Fetch-Siteheader.
- 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): # ...