Skip to main content

Module csrf

Module csrf 

Source
Expand description

CSRF protection helpers.

actix-admin protects every state-changing route (POST/PUT/PATCH/DELETE) with a per-session CSRF token stored in the actix-session cookie.

  • csrf_token_for returns the current token, creating one the first time it is called for a session.
  • verify_csrf extracts the token from either the X-CSRF-Token header (used by HTMX) or the _csrf query parameter (used by classic form posts and multipart uploads, where the form body is streamed lazily by actix-multipart and cannot be peeked ahead-of-time).

The check can be globally disabled via crate::ActixAdminConfiguration::enable_csrf \u2014 in that case verify_csrf is a no-op.

Setup: install a session middleware (e.g. actix-session::CookieSession) before the admin scope, exactly like you already need to for auth.

HTMX wiring: base.html sets an htmx:configRequest listener that attaches the token as X-CSRF-Token on every HTMX call. Non-HTMX forms also include a hidden _csrf input, and delete/action URLs carry the token as a _csrf= query parameter.

Constants§

CSRF_HEADER
Header name checked on every state-changing request.
CSRF_QUERY_PARAM
Fallback query-string parameter, used when the header isn’t available (classic multipart form submissions handled by actix-multipart).
CSRF_SESSION_KEY
Session storage key. Public so applications can inspect/clear the token.

Functions§

csrf_token_for
Return the CSRF token for session, generating a fresh one if there is none. Safe to call from any handler; the value is stable for the lifetime of the session.
verify_csrf
Assert that req carries a valid CSRF token for session. Returns Ok(()) when CSRF protection is disabled globally.

Type Aliases§

CsrfError
Marker error type returned by verify_csrf. Currently equivalent to ActixAdminError with ty = ActixAdminErrorType::CsrfError \u2014 kept as a distinct alias in case a future release wants richer diagnostics.