field or ajax" /> field or ajax" /> field or ajax"/>

Dead simple CSRF security middleware for Starlette ⭐ and Fast API ⚡

Overview

csrf-starlette-fastapi

Dead simple CSRF security middleware for Starlette and Fast API

  • Will work with either a field or ajax request headers, interchangeably.
  • Uses stateless Double Submit Cookie method, like Django.
  • Tiny, easy to audit.

Install

Add csrf_middleware.py to your project /middleware folder.

Add to Starlette

from starlette.applications import Starlette
from starlette.middleware import Middleware
from middleware.csrf_middleware import CSRFMiddleware

routes = ...

middleware = [
    Middleware(CSRFMiddleware)
]

app = Starlette(routes=routes, middleware=middleware)

Add to FastAPI

from fastapi import FastAPI
from middleware.csrf_middleware import CSRFMiddleware

app = FastAPI()
app.add_middleware(CSRFMiddleware)

Usage

  • Use directly in HTML.
  • Use javascript / ajax frameworks such as the elegant htmx ♥️
  • Another htmx ♥️ solution.

Why?

To make available something more simple and auditable than the typical libraries for this as of 2022:

Do I need CSRF Middleware?

Maybe? Maybe not?

You might also like...
A FastAPI Middleware of joerick/pyinstrument to check your service performance.

fastapi_profiler A FastAPI Middleware of joerick/pyinstrument to check your service performance. 📣 Info A FastAPI Middleware of pyinstrument to check

Prometheus integration for Starlette.

Starlette Prometheus Introduction Prometheus integration for Starlette. Requirements Python 3.6+ Starlette 0.9+ Installation $ pip install starlette-p

Prometheus integration for Starlette.

Starlette Prometheus Introduction Prometheus integration for Starlette. Requirements Python 3.6+ Starlette 0.9+ Installation $ pip install starlette-p

SQLAlchemy Admin for Starlette/FastAPI
SQLAlchemy Admin for Starlette/FastAPI

SQLAlchemy Admin for Starlette/FastAPI SQLAdmin is a flexible Admin interface for SQLAlchemy models. Main features include: SQLAlchemy sync/async engi

Practice-python is a simple Fast api project for dealing with modern rest api technologies.

Practice Python Practice-python is a simple Fast api project for dealing with modern rest api technologies. Deployment with docker Go to the project r

Beyonic API Python official client library simplified examples using Flask, Django and Fast API.

Beyonic API Python Examples. The beyonic APIs Doc Reference: https://apidocs.beyonic.com/ To start using the Beyonic API Python API, you need to start

MS Graph API authentication example with Fast API

MS Graph API authentication example with Fast API What it is & does This is a simple python service/webapp, using FastAPI with server side rendering,

Fast, simple API for Apple firmwares.

Loyal Fast, Simple API for fetching Apple Firmwares. The API server is closed due to some reasons. Wait for v2 releases. Features Fetching Signed IPSW

A simple Blogging Backend app created with Fast API

This is a simple blogging app backend built with FastAPI. This project is created to simulate a real CRUD blogging system. It is built to be used by s

Comments
  • state object has no get

    state object has no get

    Did you test it before closing the other one :)

    File "/home/champ/projects/v8-starlette/./app/middleware/csrf_middleware2.py", line 29, in dispatch
        if request.state.get("post"):
      File "/home/champ/projects/v8-starlette/__pypackages__/3.10/lib/starlette/datastructures.py", line 702, in __getattr__
        raise AttributeError(message.format(self.__class__.__name__, key))
    AttributeError: 'State' object has no attribute 'get'
    
    opened by mybigman 1
  • state object has no post

    state object has no post

    File "/home/champ/projects/v8-starlette/./app/middleware/csrf_middleware2.py", line 29, in dispatch
        token_from_post   = request.state.post.get(CSRF_TOKEN_NAME, None)
      File "/home/champ/projects/v8-starlette/__pypackages__/3.10/lib/starlette/datastructures.py", line 702, in __getattr__
        raise AttributeError(message.format(self.__class__.__name__, key))
    AttributeError: 'State' object has no attribute 'post'
    
    #29
    token_from_post   = request.state.post.get(CSRF_TOKEN_NAME, None)
    
    opened by mybigman 1
  • token_from_post referenced before assignment

    token_from_post referenced before assignment

    if (str(token_from_cookie) != str(token_from_post)) and (str(token_from_cookie) != str(token_from_header)):
    UnboundLocalError: local variable 'token_from_post' referenced before assignment
    

    I believe your going to need to find another way to get the post request as I dont believe request.state has this, therefore your token_from_post is never going to be set.

    opened by mybigman 0
Owner
Nathaniel Sabanski
Full Stack Software Engineer
Nathaniel Sabanski
Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automatically use request headers such as x-request-id or x-correlation-id.

starlette context Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automat

Tomasz Wójcik 110 Feb 16, 2021
Code Specialist 27 Oct 16, 2022
Starlette middleware for Prerender

Prerender Python Starlette Starlette middleware for Prerender Documentation: https://BeeMyDesk.github.io/prerender-python-starlette/ Source Code: http

BeeMyDesk 14 May 2, 2021
Starlette middleware for Prerender

Prerender Python Starlette Starlette middleware for Prerender Documentation: https://BeeMyDesk.github.io/prerender-python-starlette/ Source Code: http

BeeMyDesk 13 Jul 27, 2020
Prometheus exporter for Starlette and FastAPI

starlette_exporter Prometheus exporter for Starlette and FastAPI. The middleware collects basic metrics: Counter: starlette_requests_total Histogram:

Steve Hillier 225 Jan 5, 2023
A rate limiter for Starlette and FastAPI

SlowApi A rate limiting library for Starlette and FastAPI adapted from flask-limiter. Note: this is alpha quality code still, the API may change, and

Laurent Savaete 562 Jan 1, 2023
Opentracing support for Starlette and FastApi

Starlette-OpenTracing OpenTracing support for Starlette and FastApi. Inspired by: Flask-OpenTracing OpenTracing implementations exist for major distri

Rene Dohmen 63 Dec 30, 2022
A rate limiter for Starlette and FastAPI

SlowApi A rate limiting library for Starlette and FastAPI adapted from flask-limiter. Note: this is alpha quality code still, the API may change, and

Laurent Savaete 154 Feb 16, 2021
Prometheus exporter for Starlette and FastAPI

starlette_exporter Prometheus exporter for Starlette and FastAPI. The middleware collects basic metrics: Counter: starlette_requests_total Histogram:

Steve Hillier 82 Feb 13, 2021
Opentracing support for Starlette and FastApi

Starlette-OpenTracing OpenTracing support for Starlette and FastApi. Inspired by: Flask-OpenTracing OpenTracing implementations exist for major distri

Rene Dohmen 26 Feb 11, 2021