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
# or
poetry add fastapi-csrf-protect

Getting Started

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

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 })

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:

pytest

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 --extras examples
  1. Running the example utilizing Context and Headers

    uvicorn examples.context:app
    
  2. Running the example utilizing Cookies

    uvicorn examples.cookies: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.2.1.tar.gz (7.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_csrf_protect-0.2.1-py3-none-any.whl (8.7 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: fastapi-csrf-protect-0.2.1.tar.gz
  • Upload date:
  • Size: 7.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.11 CPython/3.7.11 Darwin/20.6.0

File hashes

Hashes for fastapi-csrf-protect-0.2.1.tar.gz
Algorithm Hash digest
SHA256 48d1dd9d323a6e2449f0baf6d7b78a12661bc89ec3e3a8b929629b36f866ce88
MD5 68b7c58abb2c1c25c4813fdfb13e640c
BLAKE2b-256 bf8d30528ebbde04b72cc2a63ebb945a51c475576d0e2c3a9aa38996375692df

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for fastapi_csrf_protect-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 4ac1680b7dc8cc399df32dde653d4d1ffd92bec25f2ce4c4bdd881f16b32edcf
MD5 d87824147ff94178505bd4534c94432b
BLAKE2b-256 a9b43dc6bee46d508073c3ede6675725a9dd52c6219535174ad63d93c66ffac6

See more details on using hashes here.

Supported by

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