CSRF Protection#
- class quart_wtf.CSRFProtect(app: Quart | None = None)#
Enable CSRF protection globally for a Quart app.
app = Quart(__name__) csrf = CSRFProtect(app)
Checks the
csrf_tokenfield sent with forms, or theX-CSRFTokenheader sent with JavaScript requests. Render the token in templates using{{ csrf_token() }}.See the CSRF Protection documentation.
- init_app(app: Quart) None#
Initialize the CSRFProtect class with the Quart app.
- Parameters:
app – The Quart application.
- async protect() None#
Provides the CSRF protection for the app.
- exempt(view: str | Blueprint | Callable[[...], Awaitable[Any]]) str | Blueprint | Callable[[...], Awaitable[Any]]#
Mark a view or blueprint to be excluded from CSRF protection.
@app.route('/some-view', methods=['POST']) @csrf.exempt async def some_view(): ...
- ::
bp = Blueprint(…) csrf.exempt(bp)
- Argument:
view: The view function or a quart.Blueprint instance.
- class quart_wtf.CSRFError(description: str | None = None, response: Response | None = None)#
Raise if the client sends invalid CSRF data with the request. Generates a 400 Bad Request response with the failure reason by default. Customize the response by registering a handler with
quart.Quart.errorhandler().
- quart_wtf.utils.generate_csrf(secret_key: Any | None = None, token_key: Any | None = None) Any#
Generate a CSRF token. The token is cached for a request, so multiple calls to this function will generate the same token.
During testing, it might be useful to access the signed token in
g.csrf_tokenand the raw token insession['csrf_token'].- Parameters:
secret_key – Used to securely sign the token. Default is
WTF_CSRF_SECRET_KEYorSECRET_KEY.token_key – Key where token is stored in session for comparison. Default is
WTF_CSRF_FIELD_NAMEor'csrf_token'.
- quart_wtf.utils.validate_csrf(data: Any, secret_key: Any | None = None, time_limit: int | None = None, token_key: Any | None = None) None#
Check if the given data is a valid CSRF token. This compares the given signed token to the one stored in the session.
- Parameters:
data – The signed CSRF token to be checked.
secret_key – Used to securely sign the token. Default is
WTF_CSRF_SECRET_KEYorSECRET_KEY.time_limit – Number of seconds that the token is valid. Default is
WTF_CSRF_TIME_LIMITor 3600 seconds (60 minutes).token_key – Key where token is stored in session for comparison. Default is
WTF_CSRF_FIELD_NAMEor'csrf_token'.
- Raises:
ValidationError – Contains the reason that validation failed. Raises
ValidationErrorwith a specific error message rather than returningTrueorFalse.