This middleware provides various methods of CSRF protection for Starlette applications.
This section is only for Double Submit Cookie method. Other methods are not implemented yet.
- User makes a safe request (GET, HEAD, OPTIONS, TRACE) to the server.
- The server sends a cookie with a CSRF token to the client.s
- When the client makes a request that changes the server state, the server expects a CSRF token to be sent in request headers.
- Middleware checks if the token in the request headers matches the token in the cookie.
- If the tokens match, the request is processed.
- If the tokens don't match, the request is rejected with
403 Forbidden
status code.
Work in progress.
from starlette.applications import Starlette
from starlette.middleware import Middleware
from csrf_middleware import CSRFMiddleware
routes = [...]
middleware = [
Middleware(CSRFMiddleware, secret="secret-key", token_name="csrftoken")
]
app = Starlette(routes=routes, middleware=middleware)
- Implement other methods of CSRF protection.
- Double Submit Cookie
- Synchronizer Token Pattern
- Encrypted Token Pattern
- Referer Checking
- Origin Header Checking
- Write tests.
- Write documentation.
- Publish to PyPI.