session_auth

class litestar.security.session_auth.SessionAuth

Bases: Generic[UserType, BaseSessionBackendT], AbstractSecurityConfig[UserType, dict[str, Any]]

Session Based Security Backend.

session_backend_config: BaseBackendConfig[BaseSessionBackendT]

A session backend config.

retrieve_user_handler: Callable[[Any, ASGIConnection], SyncOrAsyncUnion[Any | None]]

Callable that receives the auth value from the authentication middleware and returns a user value.

Notes

  • User and Auth can be any arbitrary values specified by the security backend.

  • The User and Auth values will be set by the middleware as scope["user"] and scope["auth"] respectively. Once provided, they can access via the connection.user and connection.auth properties.

  • The callable can be sync or async. If it is sync, it will be wrapped to support async.

authentication_middleware_class

alias of SessionAuthMiddleware

guards: Iterable[Guard] | None = None

An iterable of guards to call for requests, providing authorization functionalities.

exclude: str | list[str] | None = None

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

exclude_opt_key: str = 'exclude_from_auth'

An identifier to use on routes to disable authentication and authorization checks for a particular route.

__init__(session_backend_config: BaseBackendConfig[BaseSessionBackendT], retrieve_user_handler: Callable[[Any, ASGIConnection], SyncOrAsyncUnion[Any | None]], authentication_middleware_class: type[SessionAuthMiddleware] = <class 'litestar.security.session_auth.middleware.SessionAuthMiddleware'>, guards: Iterable[Guard] | None = None, exclude: str | list[str] | None = None, exclude_opt_key: str = 'exclude_from_auth', exclude_http_methods: Sequence[Method] | None = <factory>, scopes: Scopes | None = None, route_handlers: Iterable[ControllerRouterHandler] | None = None, dependencies: dict[str, Provide] | None = None, type_encoders: TypeEncodersMap | None = None) None
scopes: Scopes | None = None

ASGI scopes processed by the authentication middleware, if None, both http and websocket will be processed.

route_handlers: Iterable[ControllerRouterHandler] | None = None

An optional iterable of route handlers to register.

dependencies: dict[str, Provide] | None = None

An optional dictionary of dependency providers.

type_encoders: TypeEncodersMap | None = None

A mapping of types to callables that transform them into types supported for serialization.

property middleware: DefineMiddleware

Use this property to insert the config into a middleware list on one of the application layers.

Examples

from typing import Any
from os import urandom

from litestar import Litestar, Request, get
from litestar_session import SessionAuth


async def retrieve_user_from_session(session: dict[str, Any]) -> Any:
    # implement logic here to retrieve a ``user`` datum given the session dictionary
    ...


session_auth_config = SessionAuth(
    secret=urandom(16), retrieve_user_handler=retrieve_user_from_session
)


@get("/")
def my_handler(request: Request) -> None: ...


app = Litestar(route_handlers=[my_handler], middleware=[session_auth_config.middleware])
Returns:

An instance of DefineMiddleware including self as the config kwarg value.

property session_backend: BaseSessionBackendT

Create a session backend.

Returns:

A subclass of BaseSessionBackend

property openapi_components: Components

Create OpenAPI documentation for the Session Authentication schema used.

Returns:

An Components instance.

property security_requirement: dict[str, list[str]]

Return OpenAPI 3.1.

SecurityRequirement for the auth backend.

Returns:

An OpenAPI 3.1 SecurityRequirement dictionary.

class litestar.security.session_auth.middleware.SessionAuthMiddleware

Bases: AbstractAuthenticationMiddleware

Session Authentication Middleware.

__init__(app: ASGIApp, exclude: str | list[str] | None, exclude_http_methods: Sequence[Method] | None, exclude_opt_key: str, retrieve_user_handler: Callable[[dict[str, Any], ASGIConnection[Any, Any, Any, Any]], Awaitable[Any]], scopes: Scopes | None) None

Session based authentication middleware.

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_http_methods – A sequence of http methods that do not require authentication.

  • exclude_opt_key – An identifier to use on routes to disable authentication and authorization checks for a particular route.

  • scopes – ASGI scopes processed by the authentication middleware.

  • retrieve_user_handler – Callable that receives the session value from the authentication middleware and returns a user value.

async authenticate_request(connection: ASGIConnection[Any, Any, Any, Any]) AuthenticationResult

Authenticate an incoming connection.

Parameters:

connection – An ASGIConnection instance.

Raises:

NotAuthorizedException – if session data is empty or user is not found.

Returns:

AuthenticationResult