Module

middleware.csrf

CSRF protection middleware — token-based, session-backed.

Generates a random token per session, validates it on state-changing requests (POST, PUT, PATCH, DELETE). Rejects with 403 if the token is missing or invalid.

RequiresSessionMiddleware— the CSRF token is stored in the session.

Usage::

from chirp.middleware.csrf import CSRFConfig, CSRFMiddleware
from chirp.middleware.sessions import SessionConfig, SessionMiddleware

app.add_middleware(SessionMiddleware(SessionConfig(secret_key="...")))
app.add_middleware(CSRFMiddleware(CSRFConfig()))

Templates::

<form method="post">
    {{ csrf_field() }}
    ...
</form>

htmx (via meta tag)::

<meta name="csrf-token" content="{{ csrf_token() }}">

Classes

CSRFConfig 5
CSRF middleware configuration.

CSRF middleware configuration.

Attributes

Name Type Description
field_name str

Form field name for the token.

header_name str

HTTP header name for AJAX/htmx requests.

session_key str

Key used to store the token in the session.

token_length int

Length of the random token in bytes (hex-encoded).

exempt_paths frozenset[str]

Paths that skip CSRF validation (e.g. API webhooks).

CSRFMiddleware 3
Token-based CSRF protection middleware. On every request: 1. Loads or generates a CSRF token in th…

Token-based CSRF protection middleware.

On every request:

  1. Loads or generates a CSRF token in the session.
  2. Makes the token available viaget_csrf_token()and template globals.
  3. On unsafe methods (POST, PUT, PATCH, DELETE), validates the token from either the form body or the request header.
  4. Rejects with 403 if the token is missing or invalid.

RequiresSessionMiddlewareto be registered first.

Attributes

Name Type Description
template_globals ClassVar[dict[str, Any]]

Methods

Internal Methods 2
__init__ 1
def __init__(self, config: CSRFConfig | None = None) -> None
Parameters
Name Type Description
config Default:None
__call__ 2 AnyResponse
Validate CSRF token on unsafe methods, then dispatch.
async
async def __call__(self, request: Request, next: Next) -> AnyResponse
Parameters
Name Type Description
request
next
Returns
AnyResponse

Functions

get_csrf_token 0 str
Return the current CSRF token. Raises ``LookupError`` if called outside a requ…
def get_csrf_token() -> str

Return the current CSRF token.

RaisesLookupErrorif called outside a request with CSRFMiddlewareactive.

Returns
str
csrf_field 0 str
Render a hidden input field with the CSRF token. For use as a template global:…
def csrf_field() -> str

Render a hidden input field with the CSRF token.

For use as a template global::

<form method="post">
    {{ csrf_field() }}
    ...
</form>

Renders:<input type="hidden" name="_csrf_token" value="...">

Returns
str
csrf_token 0 str
Return the raw CSRF token string. For use as a template global in meta tags:: …
def csrf_token() -> str

Return the raw CSRF token string.

For use as a template global in meta tags::

<meta name="csrf-token" content="{{ csrf_token() }}">
Returns
str
_validate_token 3 None
Check the CSRF token from form data or header. Raises ``HTTPError(403)`` if th…
async
async def _validate_token(request: Request, expected: str, config: CSRFConfig) -> None

Check the CSRF token from form data or header.

RaisesHTTPError(403)if the token is missing or invalid.

Parameters
Name Type Description
request Request
expected str
config CSRFConfig