jwt#
- class litestar.security.jwt.BaseJWTAuth#
- Bases: - Generic[- UserType,- TokenT],- AbstractSecurityConfig[- UserType,- TokenT]- Base class for JWT Auth backends - accepted_audiences: Sequence[str] | None = None#
- Audiences to accept when verifying the token. If given, and the audience in the token does not match, a 401 response is returned 
 - accepted_issuers: Sequence[str] | None = None#
- Issuers to accept when verifying the token. If given, and the issuer in the token does not match, a 401 response is returned 
 - create_token(identifier: str, token_expiration: timedelta | None = None, token_issuer: str | None = None, token_audience: str | None = None, token_unique_jwt_id: str | None = None, token_extras: dict | None = None, **kwargs: Any) str#
- Create a Token instance from the passed in parameters, persists and returns it. - Parameters:
- identifier¶ – Unique identifier of the token subject. Usually this is a user ID or equivalent kind of value. 
- token_expiration¶ – An optional timedelta for the token expiration. 
- token_issuer¶ – An optional value of the token - issfield.
- token_audience¶ – An optional value for the token - audfield.
- token_unique_jwt_id¶ – An optional value for the token - jtifield.
- token_extras¶ – An optional dictionary to include in the token - extrasfield.
- **kwargs¶ – Additional attributes to set on the token 
 
- Returns:
- The created token. 
 
 - format_auth_header(encoded_token: str) str#
- Format a token according to the specified OpenAPI scheme. - Parameters:
- encoded_token¶ – An encoded JWT token 
- Returns:
- The encoded token formatted for the HTTP headers 
 
 - login(identifier: str, *, response_body: Any = _EmptyEnum.EMPTY, response_media_type: str | MediaType = MediaType.JSON, response_status_code: int = 201, token_expiration: timedelta | None = None, token_issuer: str | None = None, token_audience: str | None = None, token_unique_jwt_id: str | None = None, token_extras: dict[str, Any] | None = None, send_token_as_response_body: bool = False) Response[Any]#
- Create a response with a JWT header. - Parameters:
- identifier¶ – Unique identifier of the token subject. Usually this is a user ID or equivalent kind of value. 
- response_body¶ – An optional response body to send. 
- response_media_type¶ – An optional - Content-Type. Defaults to- application/json.
- response_status_code¶ – An optional status code for the response. Defaults to - 201.
- token_expiration¶ – An optional timedelta for the token expiration. 
- token_issuer¶ – An optional value of the token - issfield.
- token_audience¶ – An optional value for the token - audfield.
- token_unique_jwt_id¶ – An optional value for the token - jtifield.
- token_extras¶ – An optional dictionary to include in the token - extrasfield.
- send_token_as_response_body¶ – If - Truethe response will be a dict including the token:- { "token": <token> }will be returned as the response body. Note: if a response body is passed this setting will be ignored.
 
- Returns:
- A - Responseinstance.
 
 - property middleware: DefineMiddleware#
- Create - JWTAuthenticationMiddlewarewrapped in- DefineMiddleware.- Returns:
- An instance of - DefineMiddleware.
 
 - property openapi_components: Components#
- Create OpenAPI documentation for the JWT auth schema used. - Returns:
- An - Componentsinstance.
 
 - require_claims: Sequence[str] | None = None#
- Require these claims to be present in the JWT payload. If any of those claims is missing, a 401 response is returned 
 - revoked_token_handler: Callable[[Any, ASGIConnection], SyncOrAsyncUnion[bool]] | None = Field(name=None,type=None,default=None,default_factory=<dataclasses._MISSING_TYPE object>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=<dataclasses._MISSING_TYPE object>,_field_type=None)#
- Callable that receives the auth value from the authentication middleware and checks whether the token has been revoked, returning True if revoked, False otherwise. 
 - property security_requirement: Dict[str, List[str]]#
- Return OpenAPI 3.1. - Returns:
- An OpenAPI 3.1 - SecurityRequirementdictionary.
 
 - strict_audience: bool = False#
- Verify that the value of the - aud(audience) claim is a single value, and not a list of values, and matches- audienceexactly. Requires that- accepted_audiencesis a sequence of length 1
 - token_secret: str#
- Key with which to generate the token hash. - Notes - This value should be kept as a secret and the standard practice is to inject it into the environment. 
 
 - retrieve_user_handler: Callable[[Any, ASGIConnection], SyncOrAsyncUnion[Any | None]]#
- Callable that receives the - authvalue from the authentication middleware and returns a- uservalue.- 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.userand- connection.authproperties.
- The callable can be sync or async. If it is sync, it will be wrapped to support async. 
 
 - auth_header: str#
- Request header key from which to retrieve the token. - E.g. - Authorizationor- X-Api-Key.
 - default_token_expiration: timedelta#
- The default value for token expiration. 
 - openapi_security_scheme_name: str#
- The value to use for the OpenAPI security scheme and security requirements. 
 - authentication_middleware_class: type[JWTAuthenticationMiddleware]#
- The authentication middleware class to use. - Must inherit from - JWTAuthenticationMiddleware
 
- class litestar.security.jwt.JWTAuth#
- Bases: - Generic[- UserType,- TokenT],- BaseJWTAuth[- UserType,- TokenT]- JWT Authentication Configuration. - This class is the main entry point to the library, and it includes methods to create the middleware, provide login functionality, and create OpenAPI documentation. - __init__(token_secret: str, retrieve_user_handler: Callable[[Any, ASGIConnection], SyncOrAsyncUnion[Any | None]], revoked_token_handler: Callable[[Any, ASGIConnection], SyncOrAsyncUnion[bool]] | None = None, 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, algorithm: str = 'HS256', auth_header: str = 'Authorization', default_token_expiration: timedelta = <factory>, openapi_security_scheme_name: str = 'BearerToken', description: str = 'JWT api-key authentication and authorization.', authentication_middleware_class: type[JWTAuthenticationMiddleware] = <class 'litestar.security.jwt.middleware.JWTAuthenticationMiddleware'>, token_cls: type[Token] = <class 'litestar.security.jwt.token.Token'>, accepted_audiences: Sequence[str] | None = None, accepted_issuers: Sequence[str] | None = None, require_claims: Sequence[str] | None = None, verify_expiry: bool = True, verify_not_before: bool = True, strict_audience: bool = False) None#
 - accepted_audiences: Sequence[str] | None = None#
- Audiences to accept when verifying the token. If given, and the audience in the token does not match, a 401 response is returned 
 - accepted_issuers: Sequence[str] | None = None#
- Issuers to accept when verifying the token. If given, and the issuer in the token does not match, a 401 response is returned 
 - auth_header: str = 'Authorization'#
- Request header key from which to retrieve the token. - E.g. - Authorizationor- X-Api-Key.
 - authentication_middleware_class#
- alias of - JWTAuthenticationMiddleware
 - description: str = 'JWT api-key authentication and authorization.'#
- Description for the OpenAPI security scheme. 
 - 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. 
 - guards: Iterable[Guard] | None = None#
- An iterable of guards to call for requests, providing authorization functionalities. 
 - openapi_security_scheme_name: str = 'BearerToken'#
- The value to use for the OpenAPI security scheme and security requirements. 
 - require_claims: Sequence[str] | None = None#
- Require these claims to be present in the JWT payload. If any of those claims is missing, a 401 response is returned 
 - revoked_token_handler: Callable[[Any, ASGIConnection], SyncOrAsyncUnion[bool]] | None = None#
- Callable that receives the auth value from the authentication middleware and checks whether the token has been revoked, returning True if revoked, False otherwise. 
 - route_handlers: Iterable[ControllerRouterHandler] | None = None#
- An optional iterable of route handlers to register. 
 - scopes: Scopes | None = None#
- ASGI scopes processed by the authentication middleware, if - None, both- httpand- websocketwill be processed.
 - strict_audience: bool = False#
- Verify that the value of the - aud(audience) claim is a single value, and not a list of values, and matches- audienceexactly. Requires that- accepted_audiencesis a sequence of length 1
 - type_encoders: TypeEncodersMap | None = None#
- A mapping of types to callables that transform them into types supported for serialization. 
 - token_secret: str#
- Key with which to generate the token hash. - Notes - This value should be kept as a secret and the standard practice is to inject it into the environment. 
 
 - retrieve_user_handler: Callable[[Any, ASGIConnection], SyncOrAsyncUnion[Any | None]]#
- Callable that receives the - authvalue from the authentication middleware and returns a- uservalue.- 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.userand- connection.authproperties.
- The callable can be sync or async. If it is sync, it will be wrapped to support async. 
 
 - default_token_expiration: timedelta#
- The default value for token expiration. 
 
- class litestar.security.jwt.JWTAuthenticationMiddleware#
- Bases: - AbstractAuthenticationMiddleware- JWT Authentication middleware. - This class provides JWT authentication functionalities. - __init__(algorithm: str, app: ASGIApp, auth_header: str, exclude: str | list[str] | None, exclude_http_methods: Sequence[Method] | None, exclude_opt_key: str, retrieve_user_handler: Callable[[Token, ASGIConnection[Any, Any, Any, Any]], Awaitable[Any]], scopes: Scopes, token_secret: str, token_cls: type[Token] = <class 'litestar.security.jwt.token.Token'>, token_audience: Sequence[str] | None = None, token_issuer: Sequence[str] | None = None, require_claims: Sequence[str] | None = None, verify_expiry: bool = True, verify_not_before: bool = True, strict_audience: bool = False, revoked_token_handler: Callable[[Token, ASGIConnection[Any, Any, Any, Any]], Awaitable[Any]] | None = None) None#
- Check incoming requests for an encoded token in the auth header specified, and if present retrieve the user from persistence using the provided function. - Parameters:
- algorithm¶ – JWT hashing algorithm to use. 
- app¶ – An ASGIApp, this value is the next ASGI handler to call in the middleware stack. 
- auth_header¶ – Request header key from which to retrieve the token. E.g. - Authorizationor- X-Api-Key.
- exclude¶ – A pattern or list of patterns to skip. 
- exclude_opt_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. 
- retrieve_user_handler¶ – A function that receives a - Tokenand returns a user, which can be any arbitrary value.
- scopes¶ – ASGI scopes processed by the authentication middleware. 
- token_secret¶ – Secret for decoding the JWT. This value should be equivalent to the secret used to encode it. 
- token_cls¶ – Token class used when encoding / decoding JWTs 
- token_audience¶ – Verify the audience when decoding the token. If the audience in the token does not match any audience given, raise a - NotAuthorizedException
- token_issuer¶ – Verify the issuer when decoding the token. If the issuer in the token does not match any issuer given, raise a - NotAuthorizedException
- require_claims¶ – Require these claims to be present in the JWT payload 
- verify_expiry¶ – Verify that the value of the - exp(expiration) claim is in the future
- verify_not_before¶ – Verify that the value of the - nbf(not before) claim is in the past
- strict_audience¶ – Verify that the value of the - aud(audience) claim is a single value, and not a list of values, and matches- audienceexactly. Requires that- accepted_audiencesis a sequence of length 1
- revoked_token_handler¶ – A function that receives a - Tokenand returns a boolean indicating whether the token has been revoked.
 
 
 - async authenticate_request(connection: ASGIConnection[Any, Any, Any, Any]) AuthenticationResult#
- Given an HTTP Connection, parse the JWT api key stored in the header and retrieve the user correlating to the token from the DB. - Parameters:
- connection¶ – An Litestar HTTPConnection instance. 
- Returns:
- AuthenticationResult 
- Raises:
- NotAuthorizedException – If token is invalid or user is not found. 
 
 - async authenticate_token(encoded_token: str, connection: ASGIConnection[Any, Any, Any, Any]) AuthenticationResult#
- Given an encoded JWT token, parse, validate and look up sub within token. - Parameters:
- Raises:
- NotAuthorizedException – If token is invalid or user is not found. 
- Returns:
- AuthenticationResult 
 
 
- class litestar.security.jwt.JWTCookieAuth#
- Bases: - Generic[- UserType,- TokenT],- BaseJWTAuth[- UserType,- TokenT]- JWT Cookie Authentication Configuration. - This class is an alternate entry point to the library, and it includes all the functionality of the - JWTAuthclass and adds support for passing JWT tokens- HttpOnlycookies.- __init__(token_secret: str, retrieve_user_handler: Callable[[Any, ASGIConnection], SyncOrAsyncUnion[Any | None]], revoked_token_handler: Callable[[Any, ASGIConnection], SyncOrAsyncUnion[bool]] | None = None, guards: Iterable[Guard] | None = None, exclude: str | list[str] | None = None, exclude_opt_key: str = 'exclude_from_auth', scopes: Scopes | None = None, exclude_http_methods: Sequence[Method] | None = <factory>, route_handlers: Iterable[ControllerRouterHandler] | None = None, dependencies: dict[str, Provide] | None = None, type_encoders: TypeEncodersMap | None = None, algorithm: str = 'HS256', auth_header: str = 'Authorization', default_token_expiration: timedelta = <factory>, openapi_security_scheme_name: str = 'BearerToken', key: str = 'token', path: str = '/', domain: str | None = None, secure: bool | None = None, samesite: Literal['lax', 'strict', 'none'] = 'lax', description: str = 'JWT cookie-based authentication and authorization.', authentication_middleware_class: type[JWTCookieAuthenticationMiddleware] = <class 'litestar.security.jwt.middleware.JWTCookieAuthenticationMiddleware'>, token_cls: type[Token] = <class 'litestar.security.jwt.token.Token'>, accepted_audiences: Sequence[str] | None = None, accepted_issuers: Sequence[str] | None = None, require_claims: Sequence[str] | None = None, verify_expiry: bool = True, verify_not_before: bool = True, strict_audience: bool = False) None#
 - accepted_audiences: Sequence[str] | None = None#
- Audiences to accept when verifying the token. If given, and the audience in the token does not match, a 401 response is returned 
 - accepted_issuers: Sequence[str] | None = None#
- Issuers to accept when verifying the token. If given, and the issuer in the token does not match, a 401 response is returned 
 - auth_header: str = 'Authorization'#
- Request header key from which to retrieve the token. - E.g. - Authorizationor- X-Api-Key.
 - authentication_middleware_class#
- alias of - JWTCookieAuthenticationMiddleware
 - description: str = 'JWT cookie-based authentication and authorization.'#
- Description for the OpenAPI security scheme. 
 - 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. 
 - guards: Iterable[Guard] | None = None#
- An iterable of guards to call for requests, providing authorization functionalities. 
 - login(identifier: str, *, response_body: Any = _EmptyEnum.EMPTY, response_media_type: str | MediaType = MediaType.JSON, response_status_code: int = 201, token_expiration: timedelta | None = None, token_issuer: str | None = None, token_audience: str | None = None, token_unique_jwt_id: str | None = None, token_extras: dict[str, Any] | None = None, send_token_as_response_body: bool = False) Response[Any]#
- Create a response with a JWT header. - Parameters:
- identifier¶ – Unique identifier of the token subject. Usually this is a user ID or equivalent kind of value. 
- response_body¶ – An optional response body to send. 
- response_media_type¶ – An optional ‘Content-Type’. Defaults to ‘application/json’. 
- response_status_code¶ – An optional status code for the response. Defaults to ‘201 Created’. 
- token_expiration¶ – An optional timedelta for the token expiration. 
- token_issuer¶ – An optional value of the token - issfield.
- token_audience¶ – An optional value for the token - audfield.
- token_unique_jwt_id¶ – An optional value for the token - jtifield.
- token_extras¶ – An optional dictionary to include in the token - extrasfield.
- send_token_as_response_body¶ – If - Truethe response will be a dict including the token:- { "token": <token> }will be returned as the response body. Note: if a response body is passed this setting will be ignored.
 
- Returns:
- A - Responseinstance.
 
 - property middleware: DefineMiddleware#
- Create JWTCookieAuthenticationMiddlewarewrapped in
 - Returns:
- An instance of - DefineMiddleware.
 
- Create 
 - property openapi_components: Components#
- Create OpenAPI documentation for the JWT Cookie auth scheme. - Returns:
- A - Componentsinstance.
 
 - openapi_security_scheme_name: str = 'BearerToken'#
- The value to use for the OpenAPI security scheme and security requirements. 
 - path: str = '/'#
- Path fragment that must exist in the request url for the cookie to be valid. - Defaults to - /.
 - require_claims: Sequence[str] | None = None#
- Require these claims to be present in the JWT payload. If any of those claims is missing, a 401 response is returned 
 - revoked_token_handler: Callable[[Any, ASGIConnection], SyncOrAsyncUnion[bool]] | None = None#
- Callable that receives the auth value from the authentication middleware and checks whether the token has been revoked, returning True if revoked, False otherwise. 
 - route_handlers: Iterable[ControllerRouterHandler] | None = None#
- An optional iterable of route handlers to register. 
 - samesite: Literal['lax', 'strict', 'none'] = 'lax'#
- Controls whether or not a cookie is sent with cross-site requests. Defaults to - lax.
 - scopes: Scopes | None = None#
- ASGI scopes processed by the authentication middleware, if - None, both- httpand- websocketwill be processed.
 - strict_audience: bool = False#
- Verify that the value of the - aud(audience) claim is a single value, and not a list of values, and matches- audienceexactly. Requires that- accepted_audiencesis a sequence of length 1
 - type_encoders: TypeEncodersMap | None = None#
- A mapping of types to callables that transform them into types supported for serialization. 
 - token_secret: str#
- Key with which to generate the token hash. - Notes - This value should be kept as a secret and the standard practice is to inject it into the environment. 
 
 - retrieve_user_handler: Callable[[Any, ASGIConnection], SyncOrAsyncUnion[Any | None]]#
- Callable that receives the - authvalue from the authentication middleware and returns a- uservalue.- 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.userand- connection.authproperties.
- The callable can be sync or async. If it is sync, it will be wrapped to support async. 
 
 - default_token_expiration: timedelta#
- The default value for token expiration. 
 
- class litestar.security.jwt.JWTCookieAuthenticationMiddleware#
- Bases: - JWTAuthenticationMiddleware- Cookie based JWT authentication middleware. - __init__(algorithm: str, app: ASGIApp, auth_cookie_key: str, auth_header: str, exclude: str | list[str] | None, exclude_opt_key: str, exclude_http_methods: Sequence[Method] | None, retrieve_user_handler: Callable[[Token, ASGIConnection[Any, Any, Any, Any]], Awaitable[Any]], scopes: Scopes, token_secret: str, token_cls: type[Token] = <class 'litestar.security.jwt.token.Token'>, token_audience: Sequence[str] | None = None, token_issuer: Sequence[str] | None = None, require_claims: Sequence[str] | None = None, verify_expiry: bool = True, verify_not_before: bool = True, strict_audience: bool = False, revoked_token_handler: Callable[[Token, ASGIConnection[Any, Any, Any, Any]], Awaitable[Any]] | None = None) None#
- Check incoming requests for an encoded token in the auth header or cookie name specified, and if present retrieves the user from persistence using the provided function. - Parameters:
- algorithm¶ – JWT hashing algorithm to use. 
- app¶ – An ASGIApp, this value is the next ASGI handler to call in the middleware stack. 
- auth_cookie_key¶ – Cookie name from which to retrieve the token. E.g. - tokenor- accessToken.
- auth_header¶ – Request header key from which to retrieve the token. E.g. - Authorizationor- X-Api-Key.
- exclude¶ – A pattern or list of patterns to skip. 
- exclude_opt_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. 
- retrieve_user_handler¶ – A function that receives a - Tokenand returns a user, which can be any arbitrary value.
- scopes¶ – ASGI scopes processed by the authentication middleware. 
- token_secret¶ – Secret for decoding the JWT. This value should be equivalent to the secret used to encode it. 
- token_cls¶ – Token class used when encoding / decoding JWTs 
- token_audience¶ – Verify the audience when decoding the token. If the audience in the token does not match any audience given, raise a - NotAuthorizedException
- token_issuer¶ – Verify the issuer when decoding the token. If the issuer in the token does not match any issuer given, raise a - NotAuthorizedException
- require_claims¶ – Require these claims to be present in the JWT payload 
- verify_expiry¶ – Verify that the value of the - exp(expiration) claim is in the future
- verify_not_before¶ – Verify that the value of the - nbf(not before) claim is in the past
- strict_audience¶ – Verify that the value of the - aud(audience) claim is a single value, and not a list of values, and matches- audienceexactly. Requires that- accepted_audiencesis a sequence of length 1
- revoked_token_handler¶ – A function that receives a - Tokenand returns a boolean indicating whether the token has been revoked.
 
 
 - async authenticate_request(connection: ASGIConnection[Any, Any, Any, Any]) AuthenticationResult#
- Given an HTTP Connection, parse the JWT api key stored in the header and retrieve the user correlating to the token from the DB. - Parameters:
- connection¶ – An Litestar HTTPConnection instance. 
- Raises:
- NotAuthorizedException – If token is invalid or user is not found. 
- Returns:
- AuthenticationResult 
 
 
- class litestar.security.jwt.OAuth2Login#
- Bases: - object- OAuth2 Login DTO 
- class litestar.security.jwt.OAuth2PasswordBearerAuth#
- Bases: - Generic[- UserType,- TokenT],- BaseJWTAuth[- UserType,- TokenT]- OAUTH2 Schema for Password Bearer Authentication. - This class implements an OAUTH2 authentication flow entry point to the library, and it includes all the functionality of the - JWTAuthclass and adds support for passing JWT tokens- HttpOnlycookies.- token_urlis the only additional argument that is required, and it should point at your login route- __init__(token_secret: str, token_url: str, retrieve_user_handler: Callable[[Any, ASGIConnection], SyncOrAsyncUnion[Any | None]], revoked_token_handler: Callable[[Any, ASGIConnection], SyncOrAsyncUnion[bool]] | None = None, 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, algorithm: str = 'HS256', auth_header: str = 'Authorization', default_token_expiration: timedelta = <factory>, openapi_security_scheme_name: str = 'BearerToken', oauth_scopes: dict[str, str] | None = None, key: str = 'token', path: str = '/', domain: str | None = None, secure: bool | None = None, samesite: Literal['lax', 'strict', 'none'] = 'lax', description: str = 'OAUTH2 password bearer authentication and authorization.', authentication_middleware_class: type[JWTCookieAuthenticationMiddleware] = <class 'litestar.security.jwt.middleware.JWTCookieAuthenticationMiddleware'>, token_cls: type[Token] = <class 'litestar.security.jwt.token.Token'>, accepted_audiences: Sequence[str] | None = None, accepted_issuers: Sequence[str] | None = None, require_claims: Sequence[str] | None = None, verify_expiry: bool = True, verify_not_before: bool = True, strict_audience: bool = False) None#
 - accepted_audiences: Sequence[str] | None = None#
- Audiences to accept when verifying the token. If given, and the audience in the token does not match, a 401 response is returned 
 - accepted_issuers: Sequence[str] | None = None#
- Issuers to accept when verifying the token. If given, and the issuer in the token does not match, a 401 response is returned 
 - auth_header: str = 'Authorization'#
- Request header key from which to retrieve the token. - E.g. - Authorizationor ‘X-Api-Key’.
 - authentication_middleware_class#
- alias of - JWTCookieAuthenticationMiddleware
 - description: str = 'OAUTH2 password bearer authentication and authorization.'#
- Description for the OpenAPI security scheme. 
 - 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. 
 - guards: Iterable[Guard] | None = None#
- An iterable of guards to call for requests, providing authorization functionalities. 
 - login(identifier: str, *, response_body: Any = _EmptyEnum.EMPTY, response_media_type: str | MediaType = MediaType.JSON, response_status_code: int = 201, token_expiration: timedelta | None = None, token_issuer: str | None = None, token_audience: str | None = None, token_unique_jwt_id: str | None = None, token_extras: dict[str, Any] | None = None, send_token_as_response_body: bool = True) Response[Any]#
- Create a response with a JWT header. - Parameters:
- identifier¶ – Unique identifier of the token subject. Usually this is a user ID or equivalent kind of value. 
- response_body¶ – An optional response body to send. 
- response_media_type¶ – An optional - Content-Type. Defaults to- application/json.
- response_status_code¶ – An optional status code for the response. Defaults to - 201.
- token_expiration¶ – An optional timedelta for the token expiration. 
- token_issuer¶ – An optional value of the token - issfield.
- token_audience¶ – An optional value for the token - audfield.
- token_unique_jwt_id¶ – An optional value for the token - jtifield.
- token_extras¶ – An optional dictionary to include in the token - extrasfield.
- send_token_as_response_body¶ – If - Truethe response will be an oAuth2 token response dict. Note: if a response body is passed this setting will be ignored.
 
- Returns:
- A - Responseinstance.
 
 - property middleware: DefineMiddleware#
- Create JWTCookieAuthenticationMiddlewarewrapped in
 - Returns:
- An instance of - DefineMiddleware.
 
- Create 
 - property oauth_flow: OAuthFlow#
- Create an OpenAPI OAuth2 flow for the password bearer authentication scheme. - Returns:
- An - OAuthFlowinstance.
 
 - property openapi_components: Components#
- Create OpenAPI documentation for the OAUTH2 Password bearer auth scheme. - Returns:
- An - Componentsinstance.
 
 - openapi_security_scheme_name: str = 'BearerToken'#
- The value to use for the OpenAPI security scheme and security requirements. 
 - path: str = '/'#
- Path fragment that must exist in the request url for the cookie to be valid. - Defaults to - /.
 - require_claims: Sequence[str] | None = None#
- Require these claims to be present in the JWT payload. If any of those claims is missing, a 401 response is returned 
 - revoked_token_handler: Callable[[Any, ASGIConnection], SyncOrAsyncUnion[bool]] | None = None#
- Callable that receives the auth value from the authentication middleware and checks whether the token has been revoked, returning True if revoked, False otherwise. 
 - route_handlers: Iterable[ControllerRouterHandler] | None = None#
- An optional iterable of route handlers to register. 
 - samesite: Literal['lax', 'strict', 'none'] = 'lax'#
- Controls whether or not a cookie is sent with cross-site requests. Defaults to - lax.
 - scopes: Scopes | None = None#
- ASGI scopes processed by the authentication middleware, if - None, both- httpand- websocketwill be processed.
 - strict_audience: bool = False#
- Verify that the value of the - aud(audience) claim is a single value, and not a list of values, and matches- audienceexactly. Requires that- accepted_audiencesis a sequence of length 1
 - type_encoders: TypeEncodersMap | None = None#
- A mapping of types to callables that transform them into types supported for serialization. 
 - token_secret: str#
- Key with which to generate the token hash. - Notes - This value should be kept as a secret and the standard practice is to inject it into the environment. 
 
 - retrieve_user_handler: Callable[[Any, ASGIConnection], SyncOrAsyncUnion[Any | None]]#
- Callable that receives the - authvalue from the authentication middleware and returns a- uservalue.- 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.userand- connection.authproperties.
- The callable can be sync or async. If it is sync, it will be wrapped to support async. 
 
 - default_token_expiration: timedelta#
- The default value for token expiration. 
 
- class litestar.security.jwt.Token#
- Bases: - object- JWT Token DTO. - __init__(exp: ~datetime.datetime, sub: str, iat: ~datetime.datetime = <factory>, iss: str | None = None, aud: str | None = None, jti: str | None = None, extras: ~typing.Dict[str, ~typing.Any] = <factory>) None#
 - classmethod decode(encoded_token: str, secret: str, algorithm: str, audience: str | Sequence[str] | None = None, issuer: str | Sequence[str] | None = None, require_claims: Sequence[str] | None = None, verify_exp: bool = True, verify_nbf: bool = True, strict_audience: bool = False) Self#
- Decode a passed in token string and return a Token instance. - Parameters:
- encoded_token¶ – A base64 string containing an encoded JWT. 
- secret¶ – The secret with which the JWT is encoded. 
- algorithm¶ – The algorithm used to encode the JWT. 
- audience¶ – Verify the audience when decoding the token. If the audience in the token does not match any audience given, raise a - NotAuthorizedException
- issuer¶ – Verify the issuer when decoding the token. If the issuer in the token does not match any issuer given, raise a - NotAuthorizedException
- require_claims¶ – Verify that the given claims are present in the token 
- verify_exp¶ – Verify that the value of the - exp(expiration) claim is in the future
- verify_nbf¶ – Verify that the value of the - nbf(not before) claim is in the past
- strict_audience¶ – Verify that the value of the - aud(audience) claim is a single value, and not a list of values, and matches- audienceexactly. Requires the value passed to the- audienceto be a sequence of length 1
 
- Returns:
- A decoded Token instance. 
- Raises:
- NotAuthorizedException – If the token is invalid. 
 
 - classmethod decode_payload(encoded_token: str, secret: str, algorithms: list[str], issuer: list[str] | None = None, audience: str | Sequence[str] | None = None, options: JWTDecodeOptions | None = None) Any#
- Decode and verify the JWT and return its payload 
 - encode(secret: str, algorithm: str) str#
- Encode the token instance into a string. - Parameters:
- Returns:
- An encoded token string. 
- Raises:
- ImproperlyConfiguredException – If encoding fails.