Skip to main content

Simple integration of Cross-Site Request Forgery (XSRF) Protection by using either Cookies or Context combined with Headers

Project description

FastAPI CSRF Protect

Features


FastAPI extension that provides Cross-Site Request Forgery (XSRF) Protection support (easy to use and lightweight). 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

Usage


With Context and Headers

from fastapi import FastAPI, Request, Depends
from fastapi.responses import ORJSONResponse
from fastapi.templating import Jinja2Templates
from fastapi_csrf_protect import FastapiCsrfProtect
from fastapi_csrf_protect.exceptions import FastapiCsrfProtectError
from pydantic import BaseModel

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

class CsrfSettings(BaseModel):
  secret_key:str = 'asecrettoeverybody'

@FastapiCsrfProtect.load_config
def get_csrf_config():
  return CsrfSettings()

@app.get('/form')
def form(request: Request, csrf_protect:FastapiCsrfProtect = Depends()):
  '''
  Returns form template.
  '''
  csrf_token = csrf_protect.generate_csrf()
  response = templates.TemplateResponse('form.html', { 'request': request, 'csrf_token': csrf_token })
  return response

@app.post('/posts', response_class=ORJSONResponse)
def create_post(request: Request, csrf_protect:FastapiCsrfProtect = Depends()):
  '''
  Creates a new Post
  '''
  csrf_token = csrf_protect.get_csrf_from_headers(request.headers['X-CSRFToken'])
  csrf_protect.validate_csrf(csrf_token)
  # Do stuff

@app.exception_handler(FastapiCsrfProtectError)
def csrf_protect_exception_handler(request: Request, exc: FastapiCsrfProtectError):
  return ORJSONResponse(status_code=exc.status_code, content={ 'detail':  exc.message }) # Bad Request

With Cookies

from fastapi import FastAPI, Request, Depends
from fastapi.responses import ORJSONResponse
from fastapi.templating import Jinja2Templates
from fastapi_csrf_protect import FastapiCsrfProtect
from fastapi_csrf_protect.exceptions import FastapiCsrfProtectError
from pydantic import BaseModel

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

class CsrfSettings(BaseModel):
  secret_key:str = 'asecrettoeverybody'

@FastapiCsrfProtect.load_config
def get_csrf_config():
  return CsrfSettings()

@app.get('/form')
def form(request: Request, csrf_protect:FastapiCsrfProtect = Depends()):
  '''
  Returns form template.
  '''
  response = templates.TemplateResponse('form.html', { 'request': request })
  csrf_protect.set_csrf_cookie(response)
  return response

@app.post('/posts', response_class=ORJSONResponse)
def create_post(request: Request, csrf_protect:FastapiCsrfProtect = Depends()):
  '''
  Creates a new Post
  '''
  csrf_protect.validate_csrf_in_cookies(request)
  # Do stuff

@app.exception_handler(FastapiCsrfProtectError)
def csrf_protect_exception_handler(request: Request, exc: FastapiCsrfProtectError):
  return ORJSONResponse(status_code=exc.status_code, content={ 'detail':  exc.message }) # Bad Request

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.0.1.tar.gz (5.7 kB view details)

Uploaded Source

Built Distribution

fastapi_csrf_protect-0.0.1-py3-none-any.whl (3.1 kB view details)

Uploaded Python 3

File details

Details for the file fastapi-csrf-protect-0.0.1.tar.gz.

File metadata

  • Download URL: fastapi-csrf-protect-0.0.1.tar.gz
  • Upload date:
  • Size: 5.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.25.0 setuptools/50.3.1.post20201107 requests-toolbelt/0.9.1 tqdm/4.53.0 CPython/3.7.9

File hashes

Hashes for fastapi-csrf-protect-0.0.1.tar.gz
Algorithm Hash digest
SHA256 1b2186527b0fcafcc00b6b907874d5a387be5eee53d6a4214db62ef1e6c8ae48
MD5 ea049efb63827e9a9ebff5b27281f9ff
BLAKE2b-256 75dbd26e2e046f034e6b533d34214d2081d755e2d276c1ee96cfbd36824ad2e5

See more details on using hashes here.

File details

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

File metadata

  • Download URL: fastapi_csrf_protect-0.0.1-py3-none-any.whl
  • Upload date:
  • Size: 3.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.25.0 setuptools/50.3.1.post20201107 requests-toolbelt/0.9.1 tqdm/4.53.0 CPython/3.7.9

File hashes

Hashes for fastapi_csrf_protect-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 e5f9ec7f1e2145f9ff9daebfcd78bf9ed0f922cfc2e1e2d713c5c6c9cae8d072
MD5 53742005ebb5018e987a6c4be2ea88a3
BLAKE2b-256 963f39cb86ded539d0c265478cf6e058849143afe002c83436b223c1c93da480

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