fastapi-csrf-protect
Stateless implementation of Cross-Site Request Forgery (XSRF) Protection by using Double Submit Cookie mitigation pattern
What it is and what it does
fastapi-csrf-protect is a FastAPI extension that implements stateless Cross-Site Request Forgery (CSRF) protection using the Double Submit Cookie mitigation pattern. It generates CSRF tokens, stores them in cookies, and validates incoming requests by comparing the token in the cookie against a token in the request header or form body. The package is designed as a lightweight, easy-to-use alternative to heavier CSRF solutions, inspired by flask-wtf.
The library works by generating a pair of tokens (a plain token and a signed token), setting the signed token as a cookie, and requiring the client to send the plain token back in either an HTTP header (X-CSRFToken) or form field. A flexible mode allows accepting tokens from either location, useful for applications mixing server-side rendering with API endpoints. Configuration is done via a Pydantic settings class, and validation failures raise CsrfProtectError exceptions that can be caught with a custom exception handler.
Use it for:
- Protect FastAPI form submissions from CSRF attacks by validating tokens in POST/PUT/DELETE requests.
- Add CSRF defense to hybrid applications serving both HTML forms and JSON APIs from the same FastAPI instance.
- Migrate from flask-wtf to FastAPI while keeping a familiar CSRF protection pattern.
- Validate CSRF tokens in AJAX requests by reading them from cookies and sending them in request headers.
- Prevent token reuse by unsetting the CSRF cookie after successful form submission.
Worth the install?
AI-flagged interpretation of the facts on this page — verify before relying
Adds stateless CSRF protection to FastAPI applications using the Double Submit Cookie pattern, with support for token validation in request headers or form bodies.
Yes, with conditions. Install if you need lightweight, stateless CSRF protection in FastAPI and can accept that the package is aging (332 days since last release). The implementation is sound, dependencies are minimal, and there are no known vulnerabilities. However, verify compatibility with your FastAPI/Starlette versions and be prepared to maintain or fork if upstream updates lag behind framework changes.
Install
fastapi-csrf-protect on PyPI
pip
pip install fastapi-csrf-protectuv
uv add fastapi-csrf-protectpoetry
poetry add fastapi-csrf-protectInstalling fastapi-csrf-protect
Before you install
Low install friction with a pure-Python wheel and only four runtime dependencies (itsdangerous, pydantic, pydantic-settings, starlette). Maintenance status is aging—last release was 332 days ago—so expect slower response to issues or compatibility updates.
License in practice
MIT license (permissive) allows use in commercial and private projects with minimal restrictions; attribution required but no copyleft obligations.
Quickstart
pip install fastapi-csrf-protect
from fastapi import FastAPI, Depends, Request
from fastapi_csrf_protect import CsrfProtect
from pydantic_settings import BaseSettings
app = FastAPI()
class CsrfSettings(BaseSettings):
secret_key: str = "your-secret"
@CsrfProtect.load_config
def get_csrf_config():
return CsrfSettings()
@app.post("/submit")
async def submit(request: Request, csrf_protect: CsrfProtect = Depends()):
await csrf_protect.validate_csrf(request)
return {"status": "ok"}
Requires Python 3.9 or above; token validation is async and must be awaited.
Verify before relying
- Whether the package is actively maintained or in maintenance-only mode given the 332-day gap since last release.
- Real-world performance and security audit status of the Double Submit Cookie implementation.
- Compatibility with the latest FastAPI and Starlette versions beyond what classifiers declare.
Package facts
| License | MIT (permissive) |
| Python support | supports the current Python release (>=3.9) |
| Install friction | low — pure-Python wheel |
| Runtime dependencies | 4 — itsdangerous, pydantic-settings, pydantic, starlette |
| Maintenance | aging — 332 days since the last release |
| First released | |
| Downloads | 154,965/month — #10,835 on PyPI (30-day window, as of 2026-08-14) |
| Known vulnerabilities | none known (OSV.dev, checked 2026-08-14) |
Evidence: fastapi_csrf_protect-1.0.7-py3-none-any.whl
Keywords: asynchronous, cross-site request forgery, csrf, fastapi, samesite, starlette, xsrf
Tags
More Python Modules packages
Converts domain names between Unicode and…
permissive · top 100 on PyPI
setuptoolsSetuptools is a Python build backend and…
permissive · top 100 on PyPI
PyYAMLPyYAML parses and emits YAML 1.1 data format,…
permissive · top 100 on PyPI
pydanticPydantic validates Python data structures…
permissive · top 100 on PyPI
annotated-typesProvides reusable metadata objects for use with…
permissive · top 100 on PyPI
typing-inspectionProvides runtime tools to inspect and…
permissive · top 100 on PyPI
asgi-csrfASGI middleware that protects web applications…
permissive · top 15,000 on PyPI
starlette-csrfStarlette middleware that protects web…
permissive · top 15,000 on PyPI
fastapi-sessionsAdds session authentication to FastAPI…
permissive · top 15,000 on PyPI
flask-talismanFlask extension that automatically sets HTTP…
permissive · top 5,000 on PyPI
edx-drf-extensionsProvides JWT authentication, CSRF token…
permissive · top 15,000 on PyPI
cross-webCross provides a unified interface for writing…
permissive · top 5,000 on PyPI
safehttpxWraps httpx.AsyncClient.get() with DNS…
permissive · top 5,000 on PyPI
fastapi-loginAdds session and token-based user…
permissive · top 15,000 on PyPI
SecwebSecweb applies security headers (CSP, HSTS,…
copyleft · top 15,000 on PyPI
piccolo-apiExposes Piccolo ORM tables as REST endpoints in…
permissive · top 15,000 on PyPI