
Research
wget to Wipeout: Malicious Go Modules Fetch Destructive Payload
Socket's research uncovers three dangerous Go modules that contain obfuscated disk-wiping malware, threatening complete data loss.
fastapi-csrf-protect
Advanced tools
Stateless implementation of Cross-Site Request Forgery (XSRF) Protection by using Double Submit Cookie mitigation pattern
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
😀
fastapi-csrf-token
in cookies or serve it in template's contextThe easiest way to start working with this extension with pip
pip install fastapi-csrf-protect
# or
uv add fastapi-csrf-protect
The 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})
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.
brew install pyenv --head
curl https://pyenv.run | bash
If you do not have uv
installed, run the following command.
brew install uv
curl -LsSf https://astral.sh/uv/install.sh | sh
Once 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.
pyenv shell 3.11.9
uv venv --python-preference system
source .venv/bin/activate
To 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 --dev
Testing can be done by the following command post-installation:
uv sync --dev --extras test
pytest
generate_csrf
method has now been marked for deprecationgenerate_csrf_tokens
which returns a tuple of tokens, first unsigned
and the latter signedtoken_location
(either body
or header
) and token_key
is key
where form-encoded keeps the csrf token stored, cross-checked with csrf secret in cookies.validate_csrf
method now needs to be awaited therefore protected endpoints need to
be asynchronous as well.cookie_samesite
in settings0.3.6
generate_csrf
, please use generate_csrf_tokens
.FormData
value received for given token_key
is in fact a string, not UploadFile
Secure
and / or SameSite=None
SameSite
options and Secure
usagehttps
tests using manual test_client.base_url = 'https://testserver'
LoadConfig
mypyc
compilation; Failed due to dependency injection patternpy.typed
to projectTo 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 --extras examples
Running the example utilizing form submission
uvicorn examples.body:app
Running the example utilizing headers via JavaScript
uvicorn examples.header:app
This project is licensed under the terms of the MIT license.
FAQs
Stateless implementation of Cross-Site Request Forgery (XSRF) Protection by using Double Submit Cookie mitigation pattern
We found that fastapi-csrf-protect demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Socket's research uncovers three dangerous Go modules that contain obfuscated disk-wiping malware, threatening complete data loss.
Research
Socket uncovers malicious packages on PyPI using Gmail's SMTP protocol for command and control (C2) to exfiltrate data and execute commands.
Product
We redesigned Socket's first logged-in page to display rich and insightful visualizations about your repositories protected against supply chain threats.