FastAPI extension that provides stateless Cross-Site Request Forgery (XSRF) Protection support.
Aimed to be easy to use and lightweight, we adopt Double Submit Cookie mitigation pattern.
If you were familiar with flask-wtf library this extension suitable for you.
This extension inspired by fastapi-jwt-auth π
- Storing
fastapi-csrf-tokenin cookies or serve it in template's context
The easiest way to start working with this extension with pip
pip install fastapi-csrf-protect
# or
uv add fastapi-csrf-protectThe following examples show you how to integrate this extension to a FastAPI App
from fastapi import FastAPI, Request, Depends
from fastapi.responses import JSONResponse
from fastapi.templating import Jinja2Templates
from fastapi_csrf_protect import CsrfProtect
from fastapi_csrf_protect.exceptions import CsrfProtectError
from pydantic_settings import BaseSettings
app = FastAPI()
templates = Jinja2Templates(directory="templates")
class CsrfSettings(BaseSettings):
secret_key: str = "asecrettoeverybody"
cookie_samesite: str = "none"
@CsrfProtect.load_config
def get_csrf_config():
return CsrfSettings()
@app.get("/login")
def form(request: Request, csrf_protect: CsrfProtect = Depends()):
"""
Returns form template.
"""
csrf_token, signed_token = csrf_protect.generate_csrf_tokens()
response = templates.TemplateResponse(
"form.html", {"request": request, "csrf_token": csrf_token}
)
csrf_protect.set_csrf_cookie(signed_token, response)
return response
@app.post("/login", response_class=JSONResponse)
async def create_post(request: Request, csrf_protect: CsrfProtect = Depends()):
"""
Creates a new Post
"""
await csrf_protect.validate_csrf(request)
response: JSONResponse = JSONResponse(status_code=200, content={"detail": "OK"})
csrf_protect.unset_csrf_cookie(response) # prevent token reuse
return response
@app.exception_handler(CsrfProtectError)
def csrf_protect_exception_handler(request: Request, exc: CsrfProtectError):
return JSONResponse(status_code=exc.status_code, content={"detail": exc.message})<form method="post" action="/login">
<input type="hidden" name="token_key" value="{{ csrf_token }}">
<!-- other fields -->
</form>fetch("/items/123", {
method: "DELETE",
headers: {
"X-CSRFToken": getCookie("csrftoken")
},
credentials: "include"
});Important
- The flexible sub-package ignores the token_location setting β tokens from either header or body are always accepted.
- CSRF token validation still requires a matching CSRF cookie as in the base package.
- Priority is given to header over body when both are present.
Some applications combine Server-Side Rendering (SSR) with API endpoints in the same project. For example:
- SSR pages rendered with Jinja2 templates that use HTML forms (CSRF token in form body)
- AJAX / API calls (e.g. DELETE, PUT, PATCH) that pass the CSRF token in the HTTP header
The main fastapi-csrf-protect package is opinionated and expects the CSRF token in one location only (either header or body). For hybrid apps, this can be inconvenient.
The flexible sub-package provides a drop-in replacement for CsrfProtect that always accepts CSRF tokens from either the header or the form body, with the following priority:
- Header: X-CSRFToken
- Body: token_key (form-data)
Use fastapi_csrf_protect.flexible if:
- You have both SSR pages and API endpoints in the same project.
- Some requests (like DELETE) cannot send a body but still require CSRF validation.
- You want to avoid maintaining two different CSRF configurations.
If your app only uses one method to send CSRF tokens, stick to the core package for a stricter policy.
The following guide walks through setting up your local working environment using pyenv
as Python version manager and uv as Python package manager. If you do not have pyenv
installed, run the following command.
Install using Homebrew (Darwin)
brew install pyenv --headInstall using standalone installer (Darwin and Linux)
curl https://pyenv.run | bashIf you do not have uv installed, run the following command.
Install using Homebrew (Darwin)
brew install uvInstall using standalone installer (Darwin and Linux)
curl -LsSf https://astral.sh/uv/install.sh | shOnce you have pyenv Python version manager installed, you can
install any version of Python above version 3.9 for this project.
The following commands help you set up and activate a Python virtual
environment where uv can download project dependencies from the PyPI
open-sourced registry defined under pyproject.toml file.
Set up environment and synchronize project dependencies
pyenv shell 3.11.9
uv venv --python-preference system
source .venv/bin/activateTo contribute to the project, fork the repository and clone to your local device and install preferred testing dependency pytest Alternatively, run the following command on your terminal to do so:
uv sync --devTesting can be done by the following command post-installation:
uv sync --dev --group=tests
pytest- The
generate_csrfmethod has now been marked for deprecation - The recommended method is now
generate_csrf_tokenswhich returns a tuple of tokens, first unsigned and the latter signed - Recommended pattern is for the first token is aimed for returning as part of context
- Recommended pattern is for the signed token to be set in client's cookie completing Double Submit Cookie
- To prevent token reuse, protected endpoint can unset the signed CSRF Token in client's cookies as per example code and recommended pattern.
- New keys are added at setup
token_location(eitherbodyorheader) andtoken_keyis key where form-encoded keeps the csrf token stored, cross-checked with csrf secret in cookies. - Asynchronous
validate_csrfmethod now needs to be awaited therefore protected endpoints need to be asynchronous as well.
- Made a blunder when updating from Pydantic V1 to Pydantic V2 and caused an error to occur when
setting
cookie_samesitein settings - Fixed in version
0.3.6
- Remove deprecated method
generate_csrf, please usegenerate_csrf_tokens. - Validate
FormDatavalue received for giventoken_keyis in fact a string, notUploadFile
- Fix cookie unsetting when configuring library with cookie
Secureand / orSameSite=None - Test cookie settings covering
SameSiteoptions andSecureusage - Bypass
httpstests using manualtest_client.base_url = 'https://testserver'
- Improve boolean handling for
LoadConfig
- Attempted to make
mypyccompilation; Failed due to dependency injection pattern - Add
py.typedto project
- Add submodule
flexiblewhereCsrfProtectdoes not pre-determinetoken_key&token_location - Test
fastapi_csrf_protect.flexible.CsrfProtectwith runtime variabletoken_location
- Remove
@dataclasscode leftover frommypycexperiment - Clarify failure reasons under
tests/load_config.pyandtests/flexible/load_config.py
To run the provided examples, first you must install extra dependencies uvicorn and jinja2 Alternatively, run the following command on your terminal to do so
uv sync --group=examplesRunning the example utilizing form submission
uvicorn examples.body:appRunning the example utilizing headers via JavaScript
uvicorn examples.header:appThis project is licensed under the terms of the MIT license.