djblets.webapi.auth.backends.api_tokens¶
Authentication support for using API tokens.
This provides two classes needed for integrating API token support.
TokenAuthBackendMixin
must be subclassed or mixed into an
authentication backend and registered in
AUTHENTICATION_BACKENDS
.
WebAPITokenAuthBackend
must then be added to the API authentication
list at settings.WEB_API_AUTH_BACKENDS
.
- class TokenAuthValidateResult[source]¶
Bases:
TypedDict
The result of token validation on a Django auth backend.
New in version 3.2.
- error_message: Optional[str]¶
The error message to return if authentication failed.
This can be
None
if it succeeded, or if it failed and the default error fromLOGIN_FAILED
should be used.
- headers: Optional[Dict[str, str]]¶
Any HTTP headers to return in the response.
This can be
None
if no headers need to be returned, or if it failed and default headers fromLOGIN_FAILED
should be used.
- __annotations__ = {'error_message': ForwardRef('Optional[str]', module='djblets.webapi.auth.backends.api_tokens'), 'headers': ForwardRef('Optional[WebAPIResponseHeaders]', module='djblets.webapi.auth.backends.api_tokens')}¶
- __closed__ = False¶
- __extra_items__ = None¶
- __mutable_keys__ = frozenset({'error_message', 'headers'})¶
- __optional_keys__ = frozenset({})¶
- __orig_bases__ = (<function TypedDict>,)¶
- __readonly_keys__ = frozenset({})¶
- __required_keys__ = frozenset({'error_message', 'headers'})¶
- __total__ = True¶
- class ValidateTokenAuthBackend(*args, **kwargs)[source]¶
Bases:
Protocol
Protocol representing auth backends supporting token validation.
New in version 3.2.
- validate_token(request: HttpRequest, token: str) Optional[TokenAuthValidateResult] [source]¶
Validate a token for authentication.
- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.token (
str
) – The token to validate. This may beNone
.
- __abstractmethods__ = frozenset({})¶
- __annotations__ = {}¶
- __init__(*args, **kwargs)¶
- __non_callable_proto_members__ = {}¶
- __parameters__ = ()¶
- __protocol_attrs__ = {'validate_token'}¶
- classmethod __subclasshook__(other)¶
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).
- class TokenAuthBackendMixin[source]¶
Bases:
object
Mixin for a standard auth backend for API token authentication.
This will handle authenticating users and their API tokens for API requests. It’s only used for API requests that specify a username and a token.
This class is meant to be subclassed and mixed in to another Django auth backend (note: not a
WebAPIAuthBackend
).Subclasses must define
api_token_model
.- api_token_model: Optional[Type[BaseWebAPIToken]] = None¶
The API token model to use for any token lookups.
- Type:
- authenticate(request: HttpRequest, token: Optional[str] = None, **kwargs) Optional[Tuple[bool, Optional[str], Optional[Dict[str, str]]]] [source]¶
Authenticate a user, given a token ID.
- Parameters:
request (
django.http.HttpRequest
, unused) – The request object.token (
unicode
, optional) – The API token ID to authenticate with.**kwargs (
dict
, unused) – Keyword arguments for future expansion.
- Returns:
The resulting user, if a token matched, or
None
otherwise.- Return type:
- validate_token(request: HttpRequest, token: str) Optional[TokenAuthValidateResult] [source]¶
Check that the token is valid to use for authentication.
This will check if the token is invalid or expired. If so it will return a dictionary containing an error message with details on whether the token is invalid or expired and any appropriate HTTP headers to send to the client. If the token is valid to use for authentication this will return
None
.New in version 3.0.
- Parameters:
request (
django.http.HttpRequest
) – The request object.token (
str
) – The API token ID to validate.
- Returns:
A dictionary containing the following keys:
- Keys:
These are meant to be used as the
error_message
andheader
values in the return type ofdjblets.webapi.auth. backends.base.WebAPIAuthBackend.authenticate()
.If the token is valid to use for authentication this will return
None
.- Return type:
- __annotations__ = {'api_token_model': 'Optional[Type[BaseWebAPIToken]]'}¶
- class WebAPITokenAuthBackend[source]¶
Bases:
WebAPIAuthBackend
Authenticates users using their generated API token.
This will check the
HTTP_AUTHORIZATION
header for atoken <token>
value. If found, it will attempt to find the user that owns the token, and authenticate that user.- get_credentials(request: HttpRequest) Optional[Union[Tuple[bool, Optional[str], Optional[Dict[str, str]]], Dict[str, Any]]] [source]¶
Return credentials for the token.
If the request is attempting to authenticate with a token, this will return a dictionary containing the token in a
token
key.- Parameters:
request (
HttpRequest
) – The HTTP request from the client.- Returns:
A dictionary containing the token in a
token
key, if the client requested a token for authentication.- Return type:
- login_with_credentials(request: HttpRequest, **credentials) Tuple[bool, Optional[str], Optional[Dict[str, str]]] [source]¶
Log the user in with the given credentials.
This performs the standard authentication operations, and then stores some session state for any restrictions specified by the token.
- Parameters:
request (
HttpRequest
) – The HTTP request from the client.credentials (
dict
) – The credentials data from the request.
- Returns:
See the return type in
djblets.webapi.auth.backends. base.WebAPIAuthBackend.authenticate()
.- Return type:
- validate_credentials(request: HttpRequest, **credentials) Optional[Tuple[bool, Optional[str], Optional[Dict[str, str]]]] [source]¶
Validate that credentials are valid.
This will run through authentication backends to check whether the API token is valid to use. If the token is not valid to use this will stop the authentication process and return a message and headers on why it cannot be used.
New in version 3.0.
- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.credentials (
dict
) – All credentials provided byget_credentials()
.
- Returns:
See the return type in
WebAPIAuthBackend.authenticate()
.- Return type:
- __annotations__ = {}¶