Skip to main content

csrf_protection_middleware

Function csrf_protection_middleware 

Source
pub async fn csrf_protection_middleware(
    request: Request,
    next: Next,
) -> Result<Response, StatusCode>
Expand description

Middleware that rejects state-changing cross-origin browser requests, protecting cookie-authenticated UI routes against CSRF.

The auth cookie is HttpOnly + SameSite=Lax, which already keeps browsers from attaching it to cross-site POSTs. This adds an independent layer based on metadata browsers attach automatically:

  • Sec-Fetch-Site (all modern browsers): only same-origin and user-initiated (none) requests are allowed. Unlike SameSite=Lax, this also rejects requests from sibling subdomains (same-site).
  • Origin (legacy browsers send it on all cross-site POSTs): its authority must match the request’s Host.

Requests carrying neither header (curl and other non-browser clients) pass through; they don’t attach cookies ambiently, so CSRF does not apply to them.