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: SmarterMiddlewareMixin

Middleware 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’s last_login, rotated the session and the CSRF token, and sent user_logged_in, on every api request.

Both request.user and the async request.auser() return the user, as they would after a login, e.g. for the logging context middleware.

Parameters:
  • request – The request.

  • user (User) – The token’s user.

Return type:

None

static authenticate_request(request)[source]

Authenticate the request’s token with SmarterTokenAuthentication, and set request.auth.

Parameters:

request (HttpRequest) – The request.

Return type:

tuple[User, SmarterAuthToken]

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:

HttpRequest

Returns:

The same request.

extract_token(authorization_header)[source]

Extract the token from an Authorization header of the form <prefix> <token>.

The prefix is compared with knox’s AUTH_HEADER_PREFIX without regard to case.

Parameters:

authorization_header (str) – The header, or an empty string.

Return type:

str | None

Returns:

The token, or None if the header is empty, malformed, or has another prefix.

property formatted_class_name: str

The middleware’s dotted class name, formatted for log messages.

static get_auth_prefix()[source]

Return knox’s AUTH_HEADER_PREFIX, e.g. Token, as a string.

Return type:

str

Returns:

The prefix that an Authorization header’s token must follow.

static get_authorization_header(request)[source]

Return the request’s Authorization header as a string.

Parameters:

request (HttpRequest) – The request.

Return type:

str

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:
Return type:

SmarterJournaledJsonErrorResponse

Returns:

The 401 SmarterJournaledJsonErrorResponse.

static is_api_request(url)[source]

Return whether a url is a Smarter api endpoint.

Parameters:

url (str) – The absolute url.

Return type:

bool

Returns:

True for an api endpoint.

process_request(request)[source]

Authenticate an api request that carries a token in its Authorization header.

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_AUTH waffle switch is active.

Parameters:

request (HttpRequest) – The request.

Return type:

HttpResponseBase | Awaitable[HttpResponseBase]

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 a digest is looked up by its digest.

Return type:

None