Skip to main content

Stateless implementation of Cross-Site Request Forgery (XSRF) Protection by using Double Submit Cookie mitigation pattern

Project description

FastAPI CSRF Protect

Build Status Package Vesion Format Python Version License

Features

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-token in cookies or serve it in template's context

Installation

The easiest way to start working with this extension with pip

pip install fastapi-csrf-protect
# or
poetry add fastapi-csrf-protect

Getting Started

The following examples show you how to integrate this extension to a FastAPI App

Example Login Form

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 import BaseModel

app = FastAPI()
templates = Jinja2Templates(directory="templates")

class CsrfSettings(BaseModel):
  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})

Contributions

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:

pip install -U poetry
poetry install

Testing can be done by the following command post-installation:

poetry install --with test
pytest

Changelog

🚧 Breaking Changes (0.3.0 -> 0.3.1) The double submit update

  • The generate_csrf method has now been marked for deprecation
  • The recommended method is now generate_csrf_tokens which 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.

🚧 Breaking Changes (0.3.1 -> 0.3.2) The anti-JavaScript update

  • New keys are added at setup token_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.
  • Asynchronous validate_csrf method now needs to be awaited therefore protected endpoints need to be asynchronous as well.

Run Examples

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

poetry install --with examples

Running the example utilizing form submission

uvicorn examples.body:app

Running the example utilizing headers via JavaScript

uvicorn examples.header:app

License

This project is licensed under the terms of the MIT license.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_csrf_protect-0.3.3.tar.gz (8.9 kB view details)

Uploaded Source

Built Distribution

fastapi_csrf_protect-0.3.3-py3-none-any.whl (9.7 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_csrf_protect-0.3.3.tar.gz.

File metadata

  • Download URL: fastapi_csrf_protect-0.3.3.tar.gz
  • Upload date:
  • Size: 8.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.7.0 CPython/3.10.13 Darwin/22.1.0

File hashes

Hashes for fastapi_csrf_protect-0.3.3.tar.gz
Algorithm Hash digest
SHA256 c946288cca22b0d8c65c7252030f3e931ee2f9c24a621bbb4bc56c29c729a938
MD5 5665120e10410549506b48539fae18d7
BLAKE2b-256 f374611bf8ed4e2a43b95c75fe34d16caadecd0959a52e87499de430adebdca6

See more details on using hashes here.

File details

Details for the file fastapi_csrf_protect-0.3.3-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_csrf_protect-0.3.3-py3-none-any.whl
Algorithm Hash digest
SHA256 6145de11d592c7e8c167dbf7bd7d0656b2da272dabe87bd98b694e590001f264
MD5 c0085fcd8aa9f61da584ea41c6601e4b
BLAKE2b-256 d87f8794338210788600b1d8fdd236cee3db03ae901d08031634c166afc2e87c

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page