THE ORIONIS API
Build with clarity.
Explore the building blocks of an async-first Python framework. Every module, class, and method — connected, searchable, and ready to build with.
class CSRFTokenMiddleware(BaseMiddleware): (source)
Constructor: CSRFTokenMiddleware(config)
Web-layer middleware that enforces Cross-Site Request Forgery protection.
Design decisions
- Session-bound token — an existing token is reused while its session value is truthy. session.regenerate() requests an identifier rotation and preserves the token along with the other session data. SessionGuard.login() explicitly replaces the token; logout invalidates the session and clears it. This middleware creates a token when the configured session key is missing or has a falsy value.
- Cryptographic token — secrets.token_urlsafe(n) produces URL-safe Base-64 output from the OS CSPRNG. 32 bytes → 256 bits of entropy, well above the OWASP minimum.
- Timing-safe comparison — secrets.compare_digest() is used exclusively; plain == is never used.
- Header-first extraction — X-CSRF-Token and X-XSRF-Token are checked before touching the body. Body parsing is skipped entirely when the token is already present in a header, avoiding unnecessary I/O on API-style clients.
- XSRF-TOKEN cookie — opt-in double-submit cookie pattern for Angular, Axios, and other JavaScript frameworks. The cookie is intentionally not HttpOnly so client scripts can read it.
- Immediate exit paths — the hot path bails out as early as possible for safe methods and disabled middleware, adding near-zero overhead for the common GET case. Route-level exclusions are handled by the router (don't add the middleware to those routes).
- No global state — all request-scoped data flows through request.state; the middleware instance itself is stateless.
| Async Static Method | __extract |
Return the CSRF token from the parsed form body, or None. |
| Static Method | __extract |
Return the CSRF token from the request headers, or None. |
| Method | __attach |
Set the XSRF-TOKEN cookie on the outgoing response. |
| Method | __init__ |
Initialise the middleware from a raw configuration dictionary. |
| Method | __resolve |
Return the CSRF token for this session, creating it if absent. |
| Async Method | handle |
Execute the CSRF lifecycle for one HTTP request. |
| Class Variable | __slots__ |
Undocumented |
| Instance Variable | _cfg |
Undocumented |
| Instance Variable | _enabled |
Undocumented |
| Instance Variable | _session |
Undocumented |
| Instance Variable | _token |
Undocumented |
| Instance Variable | _xsrf |
Undocumented |
Return the CSRF token from the parsed form body, or None.
Only invoked for application/x-www-form-urlencoded and multipart/form-data requests; JSON and other content-types are expected to supply the token via a header. Body parsing is deliberately deferred to this point: when the token is already in a header this method is never called.
Checked field names (in order): _csrf, csrf_token.
| Parameters | |
request:Request | Incoming HTTP request. |
| Returns | |
str | None | Token string if found, otherwise None. |
Return the CSRF token from the request headers, or None.
Checks X-CSRF-Token first, then X-XSRF-Token. Header inspection is O(1) and involves no I/O, so it is always tried before the request body.
| Parameters | |
request:Request | Incoming HTTP request. |
| Returns | |
str | None | Token string if found, otherwise None. |
Set the XSRF-TOKEN cookie on the outgoing response.
The cookie is intentionally not HttpOnly so that JavaScript frameworks (Angular, Axios) can read it and forward it as the X-XSRF-Token request header.
The Secure flag is promoted to True automatically when the current request arrives over HTTPS, regardless of the cookie_secure configuration value.
| Parameters | |
request:Request | Provides the scheme to decide whether to promote the Secure flag. |
response:Response | Response to which the Set-Cookie header is appended. |
token:str | CSRF token to embed in the cookie value. |
| Returns | |
None | Undocumented |
Return the CSRF token for this session, creating it if absent.
An existing truthy token is returned unchanged, including after session.regenerate(). A new token is stored only when the configured session key is missing or has a falsy value. Login token rotation and logout clearing are handled explicitly by SessionGuard.
Without an active session, return a fresh ephemeral token for this request without persisting it.
| Parameters | |
request:Request | Current request; session is read from request.state.session. |
| Returns | |
str | URL-safe Base-64 CSRF token. |
Request, call_next: Callable[ [], Awaitable[ Response]]) -> Response:
(source)
¶
Execute the CSRF lifecycle for one HTTP request.
For safe methods the token is attached to request.state so templates can render the hidden field, and the request proceeds without any token comparison.
For unsafe methods the submitted token is extracted, compared against the session token, and CSRFTokenMismatchException is raised on mismatch before the handler is ever called.
| Parameters | |
request:Request | Incoming HTTP request with an active session available at request.state.session. |
callCallable[[], Awaitable[Response]] | No-arg async callable that advances through the rest of the middleware pipeline and into the route handler. |
| Returns | |
Response | HTTP response, optionally augmented with the XSRF-TOKEN cookie when xsrf_cookie is enabled. |
| Raises | |
CSRFTokenMismatchException | When an unsafe request does not supply a valid CSRF token. |