Token Strategies
Token strategies control how sessions are created, validated, and converted to access tokens. The strategy is configured viaHEADLESS_TOKEN_STRATEGY.
Available Strategies
SessionTokenStrategy
The default strategy uses Django session keys as tokens. Configuration- Session token = Django session key
- No access tokens generated
- Simple stateful authentication
- Suitable for mobile apps connecting to a single backend
JWTTokenStrategy
Generates JWT access and refresh tokens for stateless authentication. Configuration- Generates signed JWT access tokens
- Provides refresh tokens for token renewal
- Supports stateless or stateful validation
- Suitable for microservices and multi-backend architectures
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 ResponseUsing Session Tokens
Include the session token in subsequent requests using theX-Session-Token header.
Request Example
Session Token Lifecycle
Session tokens are tied to Django sessions:- Creation: Generated when user authenticates
- Validation: Validated on each request by looking up the session
- Expiration: Expires based on
SESSION_COOKIE_AGEsetting - Invalidation: Deleted when user logs out
JWT Access Tokens
When usingJWTTokenStrategy, 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, RS512string
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
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 refreshCustom JWT Claims
You can add custom claims to access tokens by extendingJWTTokenStrategy:
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 themeta section of authentication responses:
Using JWT Tokens
Include the access token in theAuthorization header:
Refresh Tokens
Refresh tokens are long-lived tokens used to obtain new access tokens without re-authentication.Token Refresh Flow
- Client receives access and refresh tokens after authentication
- Client uses access token for API requests
- When access token expires, client calls
/tokens/refreshwith refresh token - Server validates refresh token and returns new access token
- If rotation is enabled, server also returns new refresh token
Refresh Token Rotation
WhenHEADLESS_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
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:- 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:- Token rotated: Old token removed from session on refresh
- User logs out: Session deleted, invalidating all tokens
- Session expires: All associated tokens become invalid
- Token expires: Natural expiration based on
expclaim
Token Validation
Stateless Validation
WithHEADLESS_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
Stateful Validation
WithHEADLESS_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
Validation Flow
Session Management
Session Lookup
The token strategy provides session lookup functionality:Session Token Encryption
JWT tokens encrypt the session key in thesid 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
Custom Token Strategy
You can implement a custom token strategy by extendingAbstractTokenStrategy:
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)
- Long-lived (hours to days)
- Store securely on client (encrypted storage, keychain)
- Never expose in URLs or logs
- 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):- Tokens remain valid until expiration
- Use short-lived access tokens (5-15 minutes)
- Implement token blacklist for critical scenarios
Best Practices
- Use short access token lifetimes (5-15 minutes)
- Enable refresh token rotation for better security
- Use stateful validation for security-critical apps
- Use RS256 algorithm for JWT if tokens are validated by multiple services
- Rotate private keys periodically
- Monitor failed token validations for security incidents
- Implement rate limiting on refresh endpoint
- Use HTTPS in production
