Starlette middleware implementing Double Submit Cookie technique to mitigate CSRF
Slowing down. Last release over 3 years ago, little activity since. Fine for existing code; think twice for a new project.
pip install starlette-csrfStarlette CSRF Middleware
Starlette middleware implementing Double Submit Cookie technique to mitigate CSRF.
How it works?
- The user makes a first request with a method considered safe (by default
GET,HEAD,OPTIONS,TRACE). - It receives in response a cookie (named by default
csrftoken) which contains a secret value. - When the user wants to make an unsafe request, the server expects them to send the same secret value in a header (named by default
x-csrftoken). - The middleware will then compare the secret value provided in the cookie and the header.
- If they match, the request is processed.
- Otherwise, a
403 Forbiddenerror response is given.
This mechanism is necessary if you rely on cookie authentication in a browser. You can have more information about CSRF and Double Submit Cookie in the OWASP Cheat Sheet Series.
Installation
pip install starlette-csrf
Usage with Starlette
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette_csrf import CSRFMiddleware
routes = ...
middleware = [
Middleware(CSRFMiddleware, secret="__CHANGE_ME__")
]
app = Starlette(routes=routes, middleware=middleware)