Skip to main content
The headless API uses token-based authentication for app clients. Django-allauth provides flexible token strategies to handle session management and access token generation.

Token Strategies

Token strategies control how sessions are created, validated, and converted to access tokens. The strategy is configured via HEADLESS_TOKEN_STRATEGY.

Available Strategies

SessionTokenStrategy

The default strategy uses Django session keys as tokens. Configuration
Characteristics
  • Session token = Django session key
  • No access tokens generated
  • Simple stateful authentication
  • Suitable for mobile apps connecting to a single backend
Session Token Example

JWTTokenStrategy

Generates JWT access and refresh tokens for stateless authentication. Configuration
Characteristics
  • Generates signed JWT access tokens
  • Provides refresh tokens for token renewal
  • Supports stateless or stateful validation
  • Suitable for microservices and multi-backend architectures
Access Token Example

Session Tokens

Session tokens are required for the authentication process in app clients. They map to Django sessions and persist authentication state.

Creating Session Tokens

Session tokens are automatically created during authentication flows (login, signup) and returned in the response metadata. Example Authentication Response

Using Session Tokens

Include the session token in subsequent requests using the X-Session-Token header. Request Example

Session Token Lifecycle

Session tokens are tied to Django sessions:
  1. Creation: Generated when user authenticates
  2. Validation: Validated on each request by looking up the session
  3. Expiration: Expires based on SESSION_COOKIE_AGE setting
  4. Invalidation: Deleted when user logs out

JWT Access Tokens

When using JWTTokenStrategy, access tokens are JWT tokens that encode user identity and can be validated without database access.

JWT Configuration

Configure JWT settings in your Django settings:
string
default:"RS256"
Algorithm for signing tokens. Supported: HS256, HS512, RS256, RS512
string
Private key for RS algorithms (PEM format). For HS algorithms, uses SECRET_KEY if not provided.
int
default:"300"
Access token lifetime in seconds (default: 5 minutes)
int
default:"86400"
Refresh token lifetime in seconds (default: 24 hours)
string
default:"Bearer"
Authorization header scheme
boolean
default:"false"
Whether to validate access tokens against the session (stateful) or only verify signature (stateless)
boolean
default:"true"
Whether to issue a new refresh token on each refresh request
Example Configuration

JWT Payload Structure

Access tokens contain the following claims:
string
Subject: User ID (primary key as string)
number
Issued at: Unix timestamp
number
Expiration: Unix timestamp
string
JWT ID: Unique token identifier (UUID)
string
Session ID: Encrypted session key
string
Token use: access or refresh
Example Access Token Payload

Custom JWT Claims

You can add custom claims to access tokens by extending JWTTokenStrategy:
Then configure it:
Reserved Claims The following claims are reserved and will be overwritten:
  • iat (issued at)
  • exp (expiration)
  • sid (session ID)
  • jti (JWT ID)
  • token_use (token type)
  • sub (subject/user ID)

Obtaining JWT Tokens

JWT tokens are returned in the meta section of authentication responses:

Using JWT Tokens

Include the access token in the Authorization header:
Alternatively, use the session token header:

Refresh Tokens

Refresh tokens are long-lived tokens used to obtain new access tokens without re-authentication.

Token Refresh Flow

  1. Client receives access and refresh tokens after authentication
  2. Client uses access token for API requests
  3. When access token expires, client calls /tokens/refresh with refresh token
  4. Server validates refresh token and returns new access token
  5. If rotation is enabled, server also returns new refresh token
Refresh Request
Refresh Response

Refresh Token Rotation

When HEADLESS_JWT_ROTATE_REFRESH_TOKEN is True (default):
  • Each refresh request invalidates the old refresh token
  • A new refresh token is issued
  • Provides better security against token theft
When set to False:
  • Refresh token remains valid until expiration
  • Response contains only access_token (no new refresh token)
  • Simpler client implementation

Refresh Token Storage

Refresh tokens are stored in the Django session:
This allows:
  • Revoking all tokens by clearing session
  • Tracking active refresh tokens per session
  • Automatic cleanup on session expiration

Refresh Token Invalidation

Refresh tokens are invalidated when:
  1. Token rotated: Old token removed from session on refresh
  2. User logs out: Session deleted, invalidating all tokens
  3. Session expires: All associated tokens become invalid
  4. Token expires: Natural expiration based on exp claim

Token Validation

Stateless Validation

With HEADLESS_JWT_STATEFUL_VALIDATION_ENABLED = False (default):
  • Access tokens are validated by signature only
  • No database queries required
  • Fast and scalable
  • Tokens remain valid until expiration, even after logout
Use case: Microservices, high-scale APIs, distributed systems

Stateful Validation

With HEADLESS_JWT_STATEFUL_VALIDATION_ENABLED = True:
  • Access tokens are validated against the session
  • Requires database lookup per request
  • Tokens invalidated immediately on logout
  • More secure but slower
Use case: Single backend, security-critical applications

Validation Flow

Session Management

Session Lookup

The token strategy provides session lookup functionality:

Session Token Encryption

JWT tokens encrypt the session key in the sid claim to prevent session hijacking:
  • Session key encrypted with AES-256-CTR using SECRET_KEY
  • Random initialization vector per token
  • Even if JWT leaks, session key cannot be extracted for direct use
Implementation

Custom Token Strategy

You can implement a custom token strategy by extending AbstractTokenStrategy:
Then configure it:

Security Considerations

Token Storage

Access Tokens
  • Short-lived (5-15 minutes recommended)
  • Can be stored in memory on mobile apps
  • For web apps, consider secure storage (not localStorage)
Refresh Tokens
  • Long-lived (hours to days)
  • Store securely on client (encrypted storage, keychain)
  • Never expose in URLs or logs
Session Tokens
  • Tied to Django session lifetime
  • Store securely (same as refresh tokens)

Token Transmission

  • Always use HTTPS in production
  • Never include tokens in URLs or query parameters
  • Use proper HTTP headers (Authorization, X-Session-Token)

Token Revocation

Immediate revocation (stateful validation):
Eventual revocation (stateless validation):
  • Tokens remain valid until expiration
  • Use short-lived access tokens (5-15 minutes)
  • Implement token blacklist for critical scenarios

Best Practices

  1. Use short access token lifetimes (5-15 minutes)
  2. Enable refresh token rotation for better security
  3. Use stateful validation for security-critical apps
  4. Use RS256 algorithm for JWT if tokens are validated by multiple services
  5. Rotate private keys periodically
  6. Monitor failed token validations for security incidents
  7. Implement rate limiting on refresh endpoint
  8. Use HTTPS in production

Integration Examples

React Native

Flutter