asgi-csrf
raw JSON → 0.11 verified Mon Apr 27 auth: no python
ASGI middleware for protecting against CSRF attacks. Current version 0.11. Release cadence is irregular, last release 2023-02-06.
pip install asgi-csrf Common errors
error ImportError: cannot import name 'CsrfMiddleware' from 'asgi_csrf' ↓
cause Wrong class name used when importing.
fix
Use 'from asgi_csrf import ASGICSRFMiddleware'.
error RuntimeError: No secret provided ↓
cause Missing secret parameter when creating middleware.
fix
Pass a secret string: ASGICSRFMiddleware(app, secret='your-secret').
Warnings
breaking Version 0.11 switched from setup.py to pyproject.toml. If you depend on old build system, this may break. ↓
fix Update to 0.11 and ensure build tooling supports PEP 621.
gotcha If you do not get a CSRF token cookie set, check that your response contains a form with a CSRF hidden input, or set always_set_cookie=True. ↓
fix Add always_set_cookie=True to middleware initialization.
gotcha Requests with an Authorization: Bearer header are NOT subject to CSRF checks. This is by design but can be a footgun if you expect CSRF for API endpoints using Bearer tokens. ↓
fix Do not rely on CSRF protection for Bearer token endpoints.
deprecated The send_csrf_failed argument (custom error page) is available since 0.10. No deprecation yet, but old pattern of catching errors may break. ↓
fix Use send_csrf_failed callback instead of custom exception handling.
Imports
- ASGICSRFMiddleware wrong
from asgi_csrf import CsrfMiddlewarecorrectfrom asgi_csrf import ASGICSRFMiddleware - asgi_csrf wrong
import asgi_csrf_middlewarecorrectimport asgi_csrf
Quickstart
from asgi_csrf import ASGICSRFMiddleware
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
app = Starlette()
@app.route('/protected')
async def protected(request):
return PlainTextResponse('OK')
app = ASGICSRFMiddleware(app, secret='my-secret')