Middleware

Smarter.lib.drf.middleware

Middleware for Smarter token authentication 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 authenticate_request(request)[source]
static ensure_request_user(request)[source]
Return type:

Request

extract_token(authorization_header)[source]

Extract token from Authorization header.

Return type:

str | None

property formatted_class_name: str

Returns the class name formatted for logging.

Returns:

The formatted class name as a string.

Return type:

str

static get_auth_prefix()[source]
Return type:

str

static get_authorization_header(request)[source]
Return type:

str

handle_authentication_failure(request, token, exc)[source]
static is_api_request(url)[source]
Return type:

bool

process_request(request)[source]
sync_capable = True
validate_token_lifetime(user, auth_obj)[source]

Warn on tokens exceeding configured lifetime.

Return type:

None