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

Build Status Package Vesion Format Python Version License

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 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'

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

@app.get('/form')
def form(request: Request, csrf_protect:CsrfProtect = 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=JSONResponse)
def create_post(request: Request, csrf_protect:CsrfProtect = Depends()):
  '''
  Creates a new Post
  '''
  csrf_token = csrf_protect.get_csrf_from_headers(request.headers)
  csrf_protect.validate_csrf(csrf_token)
  # Do stuff

@app.exception_handler(CsrfProtectError)
def csrf_protect_exception_handler(request: Request, exc: CsrfProtectError):
  return JSONResponse(
    status_code=exc.status_code,
      content={ 'detail':  exc.message
    }
  )

With Cookies

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'

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

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

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

@app.exception_handler(CsrfProtectError)
def csrf_protect_exception_handler(request: Request, exc: CsrfProtectError):
  return JSONResponse(status_code=exc.status_code, content={ 'detail':  exc.message })

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

Uploaded Source

Built Distribution

fastapi_csrf_protect-0.1.4-py3-none-any.whl (8.1 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: fastapi-csrf-protect-0.1.4.tar.gz
  • Upload date:
  • Size: 6.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/3.7.3 pkginfo/1.7.0 requests/2.25.0 requests-toolbelt/0.9.1 tqdm/4.56.0 CPython/3.7.9

File hashes

Hashes for fastapi-csrf-protect-0.1.4.tar.gz
Algorithm Hash digest
SHA256 43ed04025e158a121e5c14ff7f3a2447e33b33d8b7e6d923769d1c2692e80f97
MD5 098a1b95e3bffa4ef3aaf85ea7e7ad8b
BLAKE2b-256 e776df3e207bf021b66c9655e866ffc39f8bf4b23e6d24f47316de77bb76bd68

See more details on using hashes here.

File details

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

File metadata

  • Download URL: fastapi_csrf_protect-0.1.4-py3-none-any.whl
  • Upload date:
  • Size: 8.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/3.7.3 pkginfo/1.7.0 requests/2.25.0 requests-toolbelt/0.9.1 tqdm/4.56.0 CPython/3.7.9

File hashes

Hashes for fastapi_csrf_protect-0.1.4-py3-none-any.whl
Algorithm Hash digest
SHA256 eb46ca15edf37e96bb4cd0ad05e561f56d8f22027752104cf2b3bb68536e9720
MD5 0cd51049adfd643e7381ed0d3e8e998d
BLAKE2b-256 8903bd6ecab89954cd7f62eaaa2e67aff9e79df5302c205e34a68ef9393e9ec9

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