jwt#

class starlite.contrib.jwt.JWTAuth#

Bases: Generic[UserType], AbstractSecurityConfig[UserType, Token]

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.

algorithm: str#

Algorithm to use for JWT hashing.

auth_header: str#

Request header key from which to retrieve the token.

E.g. Authorization or ‘X-Api-Key’.

default_token_expiration: timedelta#

The default value for token expiration.

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.

openapi_security_scheme_name: str#

The value to use for the OpenAPI security scheme and security requirements.

description: str#

Description for the OpenAPI security scheme.

authentication_middleware_class: Type[JWTAuthenticationMiddleware]#

The authentication middleware class to use.

Must inherit from JWTAuthenticationMiddleware

property openapi_components: Components#

Create OpenAPI documentation for the JWT auth schema used.

Returns:

An Components instance.

property security_requirement: Dict[str, List[str]]#

Return OpenAPI 3.1.

SecurityRequirement

Returns:

An OpenAPI 3.1 SecurityRequirement dictionary.

property middleware: DefineMiddleware#

Create JWTAuthenticationMiddleware wrapped in Starlite’s DefineMiddleware.

Returns:

An instance of DefineMiddleware.

login(identifier: str, *, response_body: ~typing.Any = <class 'starlite.types.empty.Empty'>, response_media_type: ~typing.Union[str, ~starlite.enums.MediaType] = MediaType.JSON, response_status_code: int = 201, token_expiration: ~typing.Optional[~datetime.timedelta] = None, token_issuer: ~typing.Optional[str] = None, token_audience: ~typing.Optional[str] = None, token_unique_jwt_id: ~typing.Optional[str] = None, send_token_as_response_body: bool = False) Response[Any]#

Create a response with a JWT header. Calls the ‘JWTAuth.store_token_handler’ to persist the token sub.

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 iss field.

  • token_audience – An optional value for the token aud field.

  • token_unique_jwt_id – An optional value for the token jti field.

  • send_token_as_response_body – If True the 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 Response instance.

create_token(identifier: str, token_expiration: Optional[timedelta] = None, token_issuer: Optional[str] = None, token_audience: Optional[str] = None, token_unique_jwt_id: Optional[str] = None) 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 iss field.

  • token_audience – An optional value for the token aud field.

  • token_unique_jwt_id – An optional value for the token jti field.

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

class starlite.contrib.jwt.JWTAuthenticationMiddleware#

Bases: AbstractAuthenticationMiddleware

JWT Authentication middleware.

This class provides JWT authentication functionalities.

__init__(app: ASGIApp, algorithm: str, auth_header: str, exclude: Optional[Union[str, List[str]]], exclude_opt_key: str, retrieve_user_handler: AsyncCallable[[Token, ASGIConnection[Any, Any, Any]], Awaitable[Any]], scopes: Scopes, token_secret: str)#

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. Authorization or ‘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.

  • retrieve_user_handler – A function that receives an instance of Token and returns a user, which can be any arbitrary value.

  • scopes – ASGI scopes processed by the authentication middleware.

  • token_secret – Secret for decoding the JWT token. This value should be equivalent to the secret used to encode it.

async authenticate_request(connection: ASGIConnection[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 Starlite HTTPConnection instance.

Returns:

AuthenticationResult

Raises:

NotAuthorizedException <starlite.exceptions.NotAuthorizedException> – If token is invalid or user is not found.

async authenticate_token(encoded_token: str, connection: ASGIConnection[Any, Any, Any]) AuthenticationResult#

Given an encoded JWT token, parse, validate and look up sub within token.

Parameters:
  • encoded_token – _description_

  • connection – An ASGI connection instance.

Raises:

NotAuthorizedException <starlite.exceptions.NotAuthorizedException> – If token is invalid or user is not found.

Returns:

_description_

Return type:

AuthenticationResult

class starlite.contrib.jwt.JWTCookieAuth#

Bases: Generic[UserType], JWTAuth[UserType]

JWT Cookie Authentication Configuration.

This class is an alternate entry point to the library, and it includes all the functionality of the JWTAuth class and adds support for passing JWT tokens HttpOnly cookies.

key: str#

Key for the cookie.

path: str#

Path fragment that must exist in the request url for the cookie to be valid.

Defaults to ‘/’.

domain: Optional[str]#

Domain for which the cookie is valid.

secure: Optional[bool]#

Https is required for the cookie.

samesite: Literal['lax', 'strict', 'none']#

Controls whether or not a cookie is sent with cross-site requests. Defaults to lax.

description: str#

Description for the OpenAPI security scheme.

authentication_middleware_class: Type[JWTCookieAuthenticationMiddleware]#

The authentication middleware class to use.

Must inherit from JWTCookieAuthenticationMiddleware

property openapi_components: Components#

Create OpenAPI documentation for the JWT Cookie auth scheme.

Returns:

An Components instance.

property middleware: DefineMiddleware#

Create JWTCookieAuthenticationMiddleware wrapped in Starlite’s DefineMiddleware.

Returns:

An instance of DefineMiddleware.

login(identifier: str, *, response_body: ~typing.Any = <class 'starlite.types.empty.Empty'>, response_media_type: ~typing.Union[str, ~starlite.enums.MediaType] = MediaType.JSON, response_status_code: int = 201, token_expiration: ~typing.Optional[~datetime.timedelta] = None, token_issuer: ~typing.Optional[str] = None, token_audience: ~typing.Optional[str] = None, token_unique_jwt_id: ~typing.Optional[str] = None, send_token_as_response_body: bool = False) Response[Any]#

Create a response with a JWT header. Calls the ‘JWTAuth.store_token_handler’ to persist the token sub.

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 iss field.

  • token_audience – An optional value for the token aud field.

  • token_unique_jwt_id – An optional value for the token jti field.

  • send_token_as_response_body – If True the 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 Response instance.

class starlite.contrib.jwt.JWTCookieAuthenticationMiddleware#

Bases: JWTAuthenticationMiddleware

Cookie based JWT authentication middleware.

__init__(algorithm: str, app: ASGIApp, auth_cookie_key: str, auth_header: str, exclude: Optional[Union[str, List[str]]], exclude_opt_key: str, retrieve_user_handler: AsyncCallable[[Token, ASGIConnection[Any, Any, Any]], Awaitable[Any]], scopes: Scopes, token_secret: str)#

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. token or accessToken.

  • auth_header – Request header key from which to retrieve the token. E.g. Authorization or ‘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.

  • retrieve_user_handler – A function that receives an instance of Token and returns a user, which can be any arbitrary value.

  • scopes – ASGI scopes processed by the authentication middleware.

  • token_secret – Secret for decoding the JWT token. This value should be equivalent to the secret used to encode it.

async authenticate_request(connection: ASGIConnection[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 Starlite HTTPConnection instance.

Returns:

AuthenticationResult

Raises:

NotAuthorizedException <starlite.exceptions.NotAuthorizedException> – If token is invalid or user is not found.

class starlite.contrib.jwt.OAuth2Login#

Bases: BaseModel

OAuth2 Login DTO

access_token: str#

Valid JWT access token

refresh_token: Optional[str]#

Optional valid refresh token JWT

expires_in: Optional[int]#

Expiration time of the token in seconds.

class starlite.contrib.jwt.OAuth2PasswordBearerAuth#

Bases: Generic[UserType], JWTCookieAuth[UserType]

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 JWTAuth class and adds support for passing JWT tokens HttpOnly cookies.

token_url is the only additional argument that is required, and it should point at your login route

token_url: str#

The URL for retrieving a new token.

oauth_scopes: Optional[Dict[str, str]]#

Oauth Scopes available for the token.

description: str#

Description for the OpenAPI security scheme.

property oauth_flow: OAuthFlow#

Create an OpenAPI OAuth2 flow for the password bearer authentication scheme.

Returns:

An OAuthFlow instance.

property openapi_components: Components#

Create OpenAPI documentation for the OAUTH2 Password bearer auth scheme.

Returns:

An Components instance.

login(identifier: str, *, response_body: ~typing.Any = <class 'starlite.types.empty.Empty'>, response_media_type: ~typing.Union[str, ~starlite.enums.MediaType] = MediaType.JSON, response_status_code: int = 201, token_expiration: ~typing.Optional[~datetime.timedelta] = None, token_issuer: ~typing.Optional[str] = None, token_audience: ~typing.Optional[str] = None, token_unique_jwt_id: ~typing.Optional[str] = None, send_token_as_response_body: bool = True) Response[Any]#

Create a response with a JWT header. Calls the ‘JWTAuth.store_token_handler’ to persist the token sub.

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 iss field.

  • token_audience – An optional value for the token aud field.

  • token_unique_jwt_id – An optional value for the token jti field.

  • send_token_as_response_body – If True the response will be an oAuth2 token response dict. Note: if a response body is passed this setting will be ignored.

Returns:

A Response instance.

class starlite.contrib.jwt.Token#

Bases: BaseModel

JWT Token DTO.

exp: datetime#

Expiration - datetime for token expiration.

iat: datetime#

Issued at - should always be current now.

sub: ConstrainedStrValue#

Subject - usually a unique identifier of the user or equivalent entity.

iss: Optional[str]#

Issuer - optional unique identifier for the issuer.

aud: Optional[str]#

Audience - intended audience.

jti: Optional[str]#

JWT ID - a unique identifier of the JWT between different issuers.

classmethod validate_exp(value: datetime) datetime#

Ensure that exp value is a future datetime.

Parameters:

value – A datetime instance.

Raises:

ValueError – if value is not a future datetime instance.

Returns:

The validated datetime.

classmethod validate_iat(value: datetime) datetime#

Ensure that iat value is a past or current datetime.

Parameters:

value – A datetime instance.

Raises:

ValueError – if value is not a past or current datetime instance.

Returns:

The validated datetime.

static decode(encoded_token: str, secret: Union[str, Dict[str, str]], algorithm: str) Token#

Decode a passed in token string and returns a Token instance.

Parameters:
  • encoded_token – A base64 string containing an encoded JWT.

  • secret – The secret with which the JWT is encoded. It may optionally be an individual JWK or JWS set dict

  • algorithm – The algorithm used to encode the JWT.

Returns:

A decoded Token instance.

Raises:

NotAuthorizedException <starlite.exceptions.NotAuthorizedException> – If token is invalid.

encode(secret: str, algorithm: str) str#

Encode the token instance into a string.

Parameters:
  • secret – The secret with which the JWT is encoded.

  • algorithm – The algorithm used to encode the JWT.

Returns:

An encoded token string.

Raises:

ImproperlyConfiguredException <starlite.exceptions.ImproperlyConfiguredException> – If encoding fails.