middleware#

class litestar.middleware.ASGIMiddleware#

Bases: ABC

An abstract base class to easily construct ASGI middlewares, providing functionality to dynamically skip the middleware based on ASGI scope["type"], handler opt keys or path patterns and a simple way to pass configuration to middlewares.

This base class does not implement an __init__ method, so subclasses are free to use it to customize the middleware’s configuration.

Important

An instance of the individual middlewares will be created once and used to build up the internal middleware stack. As such, middlewares should not be stateful, as this state will be shared across all requests. Any connection-specific state should be scoped to the handle implementation. Not doing so would typically lead to conflicting variable reads / writes across requests, and - most likely - bugs.

class MyMiddleware(ASGIMiddleware):
    scopes = (ScopeType.HTTP,)
    exclude = ("/not/this/path",)
    exclude_opt_key = "exclude_my_middleware"

    def __init__(self, my_logger: Logger) -> None:
        self.logger = logger

    async def handle(
        self, scope: Scope, receive: Receive, send: Send, next_app: ASGIApp
    ) -> None:
        self.logger.debug("Received request for path %s", scope["path"])
        await next_app(scope, receive, send)
        self.logger.debug("Processed request for path %s", scope["path"])


app = Litestar(..., middleware=[MyMiddleware(logger=my_logger)])

New in version 2.15.

__call__(app: ASGIApp) ASGIApp#

Create the actual middleware callable

abstract 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

class litestar.middleware.AbstractAuthenticationMiddleware#

Bases: ABC

Abstract AuthenticationMiddleware that allows users to create their own AuthenticationMiddleware by extending it and overriding AbstractAuthenticationMiddleware.authenticate_request().

__init__(app: ASGIApp, exclude: str | list[str] | None = None, exclude_from_auth_key: str = 'exclude_from_auth', exclude_http_methods: Sequence[Method] | None = None, scopes: Scopes | None = None) None#

Initialize AbstractAuthenticationMiddleware.

Parameters:
  • app – An ASGIApp, this value is the next ASGI handler to call in the middleware stack.

  • exclude – A pattern or list of patterns to skip in the authentication middleware.

  • exclude_from_auth_key – An identifier to use on routes to disable authentication for a particular route.

  • exclude_http_methods – A sequence of http methods that do not require authentication.

  • scopes – ASGI scopes processed by the authentication middleware.

async __call__(scope: Scope, receive: Receive, send: Send) None#

ASGI callable.

Parameters:
  • scope – The ASGI connection scope.

  • receive – The ASGI receive function.

  • send – The ASGI send function.

Returns:

None

abstract async authenticate_request(connection: ASGIConnection) AuthenticationResult#

Receive the http connection and return an AuthenticationResult.

Notes

  • This method must be overridden by subclasses.

Parameters:

connection – An ASGIConnection instance.

Raises:

NotAuthorizedException | PermissionDeniedException – if authentication fails.

Returns:

An instance of AuthenticationResult.

class litestar.middleware.AbstractMiddleware#

Bases: object

Abstract middleware providing base functionality common to all middlewares, for dynamically engaging/bypassing the middleware based on paths, opt-keys and scope types.

When implementing new middleware, this class should be used as a base.

__init__(app: ASGIApp, exclude: str | list[str] | None = None, exclude_opt_key: str | None = None, scopes: Scopes | None = None) None#

Initialize the middleware.

Parameters:
  • app – The next ASGI app to call.

  • exclude – A pattern or list of patterns to match against a request’s path. If a match is found, the middleware will be skipped.

  • exclude_opt_key – An identifier that is set in the route handler opt key which allows skipping the middleware.

  • scopes – ASGI scope types, should be a set including either or both ‘ScopeType.HTTP’ and ‘ScopeType.WEBSOCKET’.

abstract async __call__(scope: Scope, receive: Receive, send: Send) None#

Execute the ASGI middleware.

Called by the previous middleware in the stack if a response is not awaited prior.

Upon completion, middleware should call the next ASGI handler and await it - or await a response created in its closure.

Parameters:
  • scope – The ASGI connection scope.

  • receive – The ASGI receive function.

  • send – The ASGI send function.

Returns:

None

class litestar.middleware.AuthenticationResult#

Bases: object

Dataclass for authentication result.

user: Any#

The user model, this can be any value corresponding to a user of the API.

auth: Any#

The auth value, this can for example be a JWT token.

__init__(user: Any, auth: Any) None#
class litestar.middleware.DefineMiddleware#

Bases: object

Container enabling passing *args and **kwargs to Middleware class constructors and factory functions.

__init__(middleware: Callable[..., ASGIApp], *args: Any, **kwargs: Any) None#

Initialize DefineMiddleware.

Parameters:
  • middleware – A callable that returns an ASGIApp.

  • *args – Positional arguments to pass to the callable.

  • **kwargs – Key word arguments to pass to the callable.

Notes

The callable will be passed a kwarg app, which is the next ASGI app to call in the middleware stack. It therefore must define such a kwarg.

__call__(app: ASGIApp) ASGIApp#

Call the middleware constructor or factory.

Parameters:

app – An ASGIApp, this value is the next ASGI handler to call in the middleware stack.

Returns:

Calls DefineMiddleware.middleware and returns the ASGIApp created.

class litestar.middleware.MiddlewareProtocol#

Bases: Protocol

Abstract middleware protocol.

async __call__(scope: Scope, receive: Receive, send: Send) None#

Execute the ASGI middleware.

Called by the previous middleware in the stack if a response is not awaited prior.

Upon completion, middleware should call the next ASGI handler and await it - or await a response created in its closure.

Parameters:
  • scope – The ASGI connection scope.

  • receive – The ASGI receive function.

  • send – The ASGI send function.

Returns:

None

__init__(*args, **kwargs)#