Skip to content

Json Web Token Middleware


JWT Middleware

This middleware provides an authentication for endpoints


Integration with SimpleJWT The middleware works seamlessly with the CustomJWTAuthentication class and SimpleJWT settings to ensure:

Tokens are validated and refreshed correctly. Expired or blacklisted tokens are rejected at the middleware level. Example Setting for SimpleJWT:

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
    'ROTATE_REFRESH_TOKENS': True,
    'BLACKLIST_AFTER_ROTATION': True,
    ...
}

Token Blacklist Middleware Documentation

The TokenBlacklistMiddleware ensures that access tokens included in incoming requests are valid and have not been blacklisted. It intercepts requests at the middleware level and prevents further processing if a token is invalid or blacklisted.

Key Features 1. Token Validation The middleware verifies the structure and validity of access tokens in the Authorization header.

  1. Blacklist Check Checks whether the token has been blacklisted using the BlacklistedToken model.

  2. Error Handling Provides descriptive error messages for various token-related issues, such as invalid format, expired tokens, or blacklisted tokens.

  3. Graceful Degradation Allows unauthenticated requests to proceed if no Authorization header is present.

Middleware Flow

  1. The middleware retrieves the Authorization header from the incoming request.
  2. If a token is present: The middleware splits the header to extract the token. It validates the token format (Bearer ). The middleware verifies whether the token exists in the BlacklistedToken database table using the jti claim.
  3. If the token is blacklisted or invalid, the middleware returns a 401 Unauthorized response with an appropriate error message.
  4. If the token is valid or no token is provided, the request proceeds to the next middleware or view.

Usage

Authorization Header Format Requests must include an Authorization header in the following format:

Authorization: Bearer <access_token>

Blacklisting Tokens

Tokens are blacklisted when:

  • They are explicitly blacklisted by the application.
  • They are invalidated due to refresh token rotation (if BLACKLIST_AFTER_ROTATION is enabled in SIMPLE_JWT settings).

Middleware Settings

The middleware is added to the MIDDLEWARE list in the Django settings:

MIDDLEWARE = [
    # Other middleware
    'accounts.middleware.TokenBlacklistMiddleware',
]

Errors and Responses

  1. Missing or Incorrect Header Format

    • Condition: No Authorization header or an invalid format.
    • Response:
      {
      "error": "Invalid token type. Must be 'Bearer'."
      }
      
  2. Blacklisted Token

    • Condition: The token exists in the BlacklistedToken table.
    • Response
      {
      "error": "This token has been blacklisted. Log in again."
      }
      
  3. Invalid or Expired Token

    • Condition: The token is malformed or expired.
    • Response:
      {
      "error": "Invalid or Expired access token."
      }
      
  4. Unhandled Exception
    • Condition: An unexpected error occurs.
    • Response:
      {
      "error": "An unexpected error occurred."
      }