Recent cookie enhancements can solve CSRF for you:
- Set one cookie to "lax", set one cookie to "strict".
- Check for the "strict" cookie whenever there's a database write (or other sensitive action).
The "strict" cookie will not exist in situations where CSRF will be a threat.
- https://scotthelme.co.uk/csrf-is-dead/
- https://scotthelme.co.uk/csrf-is-really-dead/
- https://simonwillison.net/2021/Aug/3/samesite/
- Discussion: encode/starlette#1411
Thanks for coming. 🤔 However if you still wish to use a middleware for some reason, please continue!
Dead simple CSRF security middleware for Starlette ⭐ and Fast API ⚡
- Will work with either a
<input type="hidden">
field or ajax request headers, interchangeably. - Uses stateless Double Submit Cookie method, like Django.
- Tiny, easy to audit.
Add csrf_middleware.py
to your project /middleware
folder.
from starlette.applications import Starlette
from starlette.middleware import Middleware
from middleware.csrf_middleware import CSRFMiddleware
routes = ...
middleware = [
Middleware(CSRFMiddleware)
]
app = Starlette(routes=routes, middleware=middleware)
from fastapi import FastAPI
from middleware.csrf_middleware import CSRFMiddleware
app = FastAPI()
app.add_middleware(CSRFMiddleware)
- Directly with HTML.
- Pass
request.state.csrftoken
to your template engine. <input type="hidden" name="csrftoken" value="{{ csrftoken }}" />
- Pass
- Using htmx
♥️ :<body hx-headers='{"csrftoken": "{{ csrftoken }}"}'>
- Using Javascript frameworks:
headers: { 'csrftoken': '{{ csrftoken }}' }
To make available something more simple and auditable than the typical libraries for this as of 2022: