Skip to main content

CSRF middleware for FastAPI applications with Jinja template integration.

Project description

fastapi-csrf-jinja

fastapi-csrf-jinja is a CSRF middleware for FastAPI applications that supports tokens in both headers and HTML forms. This library is based on starlette-csrf, with additional support for Jinja template integration.

Features

  • Supports CSRF tokens in headers and HTML forms.
  • Jinja template processor for easy CSRF token management in forms.

Installation

pip install fastapi-csrf-jinja

Usage with FastAPI

from fastapi import FastAPI
from fastapi.templating import Jinja2Templates
from fastapi_csrf_jinja.middleware import FastAPICSRFJinjaMiddleware
from fastapi_csrf_jinja.jinja_processor import csrf_token_processor

app = FastAPI()

cookie_name = "your_cookie_name"
header_name = "your_header_name"

app.add_middleware(
   FastAPICSRFJinjaMiddleware, 
   secret = "your_secret",
   cookie_name = cookie_name,
   header_name = header_name,
   )

templates = Jinja2Templates(
    directory="templates", 
    context_processors=[csrf_token_processor(cookie_name, header_name)]
    )
  • Defaults to cookie_name as "csrftoken" and header_name as "x-csrftoken" if not specified.

Usage with Jinja and HTML forms

Now, the middleware integrates with a context processor, a function that returns a dictionary containing the CSRF token, CSRF input, and CSRF header for use with other tools such as HTMX.

Simply using {{ csrf_input | safe }} in each form is now sufficient to ensure a more secure web application. For example:

<form method="post">
    {{ csrf_input | safe }}
    <!-- Other form fields here -->
    <button type="submit">Submit</button>
</form>

Furthermore, we can use {{ csrf_header }} in HTMX requests. For example:

<form hx-patch="/route/edit" hx-headers='{{ csrf_header | tojson | safe }}'  hx-trigger="submit" hx-target="#yourtarget" hx-swap="outerHTML" >
    <!-- Other form fields here -->
    <button type="submit">Submit</button>
</form>

Arguments

  • secret (str): Secret to sign the CSRF token value. Be sure to choose a strong passphrase and keep it SECRET.
  • required_urls (Optional[List[re.Pattern]] - None): List of URL regexes that the CSRF check should always be enforced, no matter the method or the cookies present.
  • exempt_urls (Optional[List[re.Pattern]] - None): List of URL regexes that the CSRF check should be skipped on. Useful if you have any APIs that you know do not need CSRF protection.
  • sensitive_cookies (Set[str] - None): Set of cookie names that should trigger the CSRF check if they are present in the request. Useful if you have other authentication methods that don't rely on cookies and don't need CSRF enforcement. If this parameter is None, the default, CSRF is always enforced.
  • safe_methods (Set[str] - {"GET", "HEAD", "OPTIONS", "TRACE"}): HTTP methods considered safe which don't need CSRF protection.
  • cookie_name (str - csrftoken): Name of the cookie.
  • cookie_path str - /): Cookie path.
  • cookie_domain (Optional[str] - None): Cookie domain. If your frontend and API lives in different sub-domains, be sure to set this argument with your root domain to allow your frontend sub-domain to read the cookie on the JavaScript side.
  • cookie_secure (bool - False): Whether to only send the cookie to the server via SSL request.
  • cookie_samesite (str - lax): Samesite strategy of the cookie.
  • header_name (str - x-csrftoken): Name of the header where you should set the CSRF token.

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

Uploaded Source

Built Distribution

fastapi_csrf_jinja-0.1.1-py3-none-any.whl (6.2 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_csrf_jinja-0.1.1.tar.gz.

File metadata

  • Download URL: fastapi_csrf_jinja-0.1.1.tar.gz
  • Upload date:
  • Size: 5.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.3 CPython/3.12.2 Windows/10

File hashes

Hashes for fastapi_csrf_jinja-0.1.1.tar.gz
Algorithm Hash digest
SHA256 9e1a96d56713f67b0adc4f63ceeaa976aaec86991a1cba1deae957d1eaa9bb8f
MD5 7fb1fd7903f6e24ed28f834c4527e96e
BLAKE2b-256 f8bc4c0314c9454f637d5ddc0cc7eab4953cfcf292f3ada6c3d1c230f16b1d2d

See more details on using hashes here.

File details

Details for the file fastapi_csrf_jinja-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_csrf_jinja-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 9b8b89d624c87dd504784155eeb6a60df418097e566e15c78cb6ad5a5f5360df
MD5 16d752bf6dc1de6dd1146ba3d3b8de88
BLAKE2b-256 b1e8eec5f4bead2b7dd7bb14ee51c50e989f7b61df16e034cc5d792f36586fda

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