csrf

class litestar.middleware.csrf.CSRFMiddleware

Bases: ASGIMiddleware

CSRF Middleware class.

This Middleware protects against attacks by setting a CSRF cookie with a token and verifying it in request headers.

__init__(config: CSRFConfig) None

Initialize CSRFMiddleware.

Parameters:

config – The CSRFConfig instance.

async handle(scope: Scope, receive: Receive, send: Send, next_app: ASGIApp) None

Handle ASGI call.

Parameters:
  • scope – The ASGI connection scope.

  • receive – The ASGI receive function.

  • send – The ASGI send function

  • next_app – The next ASGI application in the middleware stack to call

create_send_wrapper(send: Send, token: str, csrf_cookie: str | None) Send

Wrap send to handle CSRF validation.

Parameters:
  • token – The CSRF token.

  • send – The ASGI send function.

  • csrf_cookie – CSRF cookie.

Returns:

An ASGI send function.