Middleware
Middleware that authenticates api requests with a Smarter api key, using SmarterTokenAuthentication.
This module provides middleware for authenticating API requests using Knox tokens and the SmarterTokenAuthentication backend. It supports both synchronous and asynchronous request handling, performs early API endpoint filtering, validates token lifetimes, and integrates with Django signals for authentication events. Structured logging is used throughout for observability, and the middleware is compatible with Django’s MiddlewareMixin.
Features
Early API endpoint filtering to minimize unnecessary authentication checks
Knox token authentication for secure API access
Token lifetime validation against configurable maximum age
Structured logging for authentication events and errors
Signal dispatching for authentication request, success, and failure
Async-compatible middleware behavior for modern Django deployments
Classes
Signals
smarter_token_authentication_request: Emitted when a token authentication attempt is made.smarter_token_authentication_success: Emitted on successful authentication.smarter_token_authentication_failure: Emitted on authentication failure.
Exceptions
SmarterTokenAuthenticationError: Raised on authentication errors.
Dependencies
Django
Django REST Framework
Knox
asgiref
smarter.common, smarter.lib, and related internal modules
- class smarter.lib.drf.middleware.SmarterTokenAuthenticationMiddleware(get_response, *args, **kwargs)[source]
Bases:
SmarterMiddlewareMixinMiddleware for token authentication using SmarterTokenAuthentication.
- async_capable = True
- static attach_user(request, user)[source]
Make a token’s user the request’s user, for this request only.
It replaces
django.contrib.auth.login(), which an api request doesn’t need: a token authenticates each request by itself.login()also wrote the user’slast_login, rotated the session and the CSRF token, and sentuser_logged_in, on every api request.Both
request.userand the asyncrequest.auser()return the user, as they would after a login, e.g. for the logging context middleware.
- static authenticate_request(request)[source]
Authenticate the request’s token with
SmarterTokenAuthentication, and setrequest.auth.- Parameters:
request (
HttpRequest) – The request.- Return type:
- Returns:
A tuple of the user and the token.
- Raises:
AuthenticationFailed – If the token is invalid or has no user.
- static ensure_request_user(request)[source]
Set the request’s user to an anonymous user when it has none.
- Parameters:
request (
HttpRequest) – The request, which is changed in place.- Return type:
- Returns:
The same request.
- extract_token(authorization_header)[source]
Extract the token from an
Authorizationheader of the form<prefix> <token>.The prefix is compared with knox’s
AUTH_HEADER_PREFIXwithout regard to case.
- static get_auth_prefix()[source]
Return knox’s
AUTH_HEADER_PREFIX, e.g.Token, as a string.- Return type:
- Returns:
The prefix that an
Authorizationheader’s token must follow.
- static get_authorization_header(request)[source]
Return the request’s
Authorizationheader as a string.- Parameters:
request (
HttpRequest) – The request.- Return type:
- Returns:
The header, or an empty string.
- handle_authentication_failure(request, token, exc)[source]
Send the authentication failure signal, and return a 401 journaled error response.
- Parameters:
request (
HttpRequest) – The request.exc (
Exception) – The authentication error.
- Return type:
- Returns:
The 401
SmarterJournaledJsonErrorResponse.
- process_request(request)[source]
Authenticate an api request that carries a token in its
Authorizationheader.Non-api requests, requests that are already authenticated, and requests without a token pass through. A valid token’s user becomes the request’s user, for this request only, and the authentication request and success signals are sent. It does nothing unless the
ENABLE_MIDDLEWARE_SMARTER_TOKEN_AUTHwaffle switch is active.- Parameters:
request (
HttpRequest) – The request.- Return type:
- Returns:
The next handler’s response (a coroutine in async mode), or a 401 journaled error response if the token fails.
- Raises:
ValueError – If the request’s url can’t be built.
- sync_capable = True
- validate_token_lifetime(user, auth_obj)[source]
Log a warning when a token is older than
smarter_api_key_max_lifetime_days.The token is not rejected; only a warning is logged.
- Parameters:
user (
User) – The authenticated user, for the log message.auth_obj (
SmarterAuthToken) – The authenticated token. Any other object with adigestis looked up by its digest.
- Return type: