Actix JWT Middleware
A full-featured JWT authentication middleware for actix-web, built on top of jsonwebtoken. Easily add login, token refresh, and authorization to your actix-web applications.
Based on appleboy/gin-jwt (ported from Gin to Echo to actix-web) with additional features adopted from labstack/echo-jwt.
Table of Contents
- Actix JWT Middleware
- Table of Contents
- Features
- Extra Features (from labstack/echo-jwt)
- Security Notice
- Installation
- Quick Start Example
- Complete Examples
- Configuration
- JWT Parsing Options
- Supporting Multiple JWT Providers
- Token Generator (Direct Token Creation)
- Redis Store Configuration
- Demo
- Understanding the Authorizer
- Cookie Token
Features
- Simple JWT authentication for actix-web
- Built-in login, refresh, and logout handlers
- Customizable authentication, authorization, and claims
- Cookie and header token support
- Easy integration and clear API
- RFC 6749 compliant refresh tokens (OAuth 2.0 standard)
- Pluggable refresh token storage (in-memory, Redis via feature gate)
- Direct token generation without HTTP middleware
- Structured
Tokentype with metadata
Extra Features (from labstack/echo-jwt)
The following features are adopted from labstack/echo-jwt, which only provides token validation. This module combines them with the full gin-jwt feature set (login, refresh, logout, token store, etc.):
| Feature | Description |
|---|---|
| Skipper | Skip middleware for specific routes (e.g. public endpoints) |
| BeforeFunc | Hook called before token extraction - useful for request preprocessing |
| SuccessHandler | Hook called after successful token validation |
| ErrorHandler | Custom error handler with access to the original error |
| ContinueOnIgnoredError | Continue to the next handler when ErrorHandler returns None - enables hybrid public/authenticated routes |
| Typed errors | TokenParsing and TokenExtraction variants on JwtError allow distinguishing between missing and invalid tokens |
Example: Hybrid Public/Authenticated Route
let mut jwt = new;
// ... standard config ...
jwt.continue_on_ignored_error = true;
jwt.error_handler = Some;
Example: Skipper
jwt.skipper = Some;
Security Notice
Critical Security Requirements
JWT Secret Security
- Minimum Requirements: Use secrets of at least 256 bits (32 bytes) in length
- Never use: Simple passwords, dictionary words, or predictable patterns
- Recommended: Generate cryptographically secure random secrets or use
RS256algorithm- Storage: Store secrets in environment variables, never hardcode in source code
- Vulnerability: Weak secrets are vulnerable to brute-force attacks (jwt-cracker)
Production Security Checklist
- HTTPS Only: Always use HTTPS in production environments
- Strong Secrets: Minimum 256-bit randomly generated secrets
- Token Expiry: Set appropriate timeout values (recommended: 15-60 minutes for access tokens)
- Secure Cookies: Enable
secure_cookie,cookie_http_only, and appropriatecookie_same_sitesettings - Environment Variables: Store sensitive configuration in environment variables
- Input Validation: Validate all authentication inputs thoroughly
OAuth 2.0 Security Standards
This library follows RFC 6749 OAuth 2.0 security standards:
- Separate Tokens: Uses distinct opaque refresh tokens (not JWT) for enhanced security
- Server-Side Storage: Refresh tokens are stored and validated server-side
- Token Rotation: Refresh tokens are automatically rotated on each use
- Improved Security: Prevents JWT refresh token vulnerabilities and replay attacks
Secure Configuration Example
use env;
use Arc;
use Duration;
use SameSite;
use ActixJwtMiddleware;
// BAD: Weak secret, insecure settings
let mut bad_jwt = new;
bad_jwt.key = b"weak".to_vec; // Too short!
bad_jwt.timeout = from_secs; // Too long!
bad_jwt.secure_cookie = false; // Insecure in production!
// GOOD: Strong security configuration
let mut jwt = new;
jwt.key = var // From environment
.expect
.into_bytes;
jwt.timeout = from_secs; // 15-minute access tokens
jwt.max_refresh = from_secs; // 1 week refresh validity
jwt.secure_cookie = true; // HTTPS only
jwt.cookie_http_only = true; // Prevent XSS
jwt.cookie_same_site = Strict; // CSRF protection
jwt.send_cookie = true; // Enable secure cookies
Installation
Add to your Cargo.toml:
[]
= { = "https://github.com/LdDl/actix-jwt" }
To enable Redis refresh token storage:
[]
= { = "https://github.com/LdDl/actix-jwt", = ["redis-store"] }
Quick Start Example
Please see the example file and you can use extract_claims to fetch user data.
use HashMap;
use env;
use Arc;
use Duration;
use ;
use ;
use Deserialize;
use ;
const IDENTITY_KEY: &str = "id";
async
async
async
async
async
Complete Examples
This repository provides several complete example implementations demonstrating different use cases:
Basic Authentication
The basic example showing fundamental JWT authentication with login, protected routes, and token validation.
OAuth SSO Integration
OAuth 2.0 Single Sign-On conceptual example supporting multiple identity providers (Google, GitHub):
- OAuth 2.0 Authorization Code Flow pattern
- CSRF protection with state tokens
- Secure token delivery for both browser and mobile apps
Token Generator
Direct token generation without HTTP middleware, perfect for:
- Programmatic authentication
- Service-to-service communication
- Testing authenticated endpoints
- Custom authentication flows
Redis Store
Demonstrates Redis integration for refresh token storage with:
- Automatic fallback to in-memory store
- Production-ready configuration examples
Redis Store (Explicit Config)
Explicit Redis configuration using RedisConfig struct with store info endpoint.
Redis TLS
Redis store with TLS configuration for secure connections.
Authorization
Advanced authorization patterns including:
- Role-based access control (admin/user/guest)
- Path-based authorization
- Multiple middleware instances
- Fine-grained permission control
Configuration
The ActixJwtMiddleware struct provides the following configuration options:
| Option | Type | Required | Default | Description |
|---|---|---|---|---|
realm |
String |
No | "actix jwt" |
Realm name to display to the user. |
signing_algorithm |
String |
No | "HS256" |
Signing algorithm (HS256, HS384, HS512, RS256, RS384, RS512). |
key |
Vec<u8> |
Yes | - | Secret key used for signing. |
timeout |
Duration |
No | 3600s (1 hour) |
Duration that a JWT access token is valid. |
max_refresh |
Duration |
No | 0 |
Duration that a refresh token is valid. |
authenticator |
Fn(&HttpRequest, &[u8]) -> Result<Value, JwtError> |
Yes | - | Callback to authenticate the user. Returns user data as serde_json::Value. |
authorizer |
Fn(&HttpRequest, &Value) -> bool |
No | true |
Callback to authorize the authenticated user. |
payload_func |
Fn(&Value) -> HashMap<String, Value> |
No | - | Callback to add additional payload data to the token. |
unauthorized |
Fn(&HttpRequest, u16, &str) -> HttpResponse |
No | default JSON | Callback for unauthorized requests. |
login_response |
Fn(&HttpRequest, &Token) -> HttpResponse |
No | default JSON | Callback for successful login response. |
logout_response |
Fn(&HttpRequest) -> HttpResponse |
No | default JSON | Callback for successful logout response. |
refresh_response |
Fn(&HttpRequest, &Token) -> HttpResponse |
No | default JSON | Callback for successful refresh response. |
identity_handler |
Fn(&HttpRequest) -> Option<Value> |
No | - | Callback to retrieve identity from claims. |
identity_key |
String |
No | "identity" |
Key used to store identity in claims. |
token_lookup |
String |
No | "header:Authorization" |
Source to extract token from (header, query, cookie). |
token_head_name |
String |
No | "Bearer" |
Header name prefix. |
time_func |
Fn() -> DateTime<Utc> |
No | Utc::now |
Function to provide current time. |
priv_key_file |
Option<String> |
No | None |
Path to private key file (for RS algorithms). |
pub_key_file |
Option<String> |
No | None |
Path to public key file (for RS algorithms). |
send_cookie |
bool |
No | false |
Whether to send token as a cookie. |
cookie_max_age |
Duration |
No | timeout |
Duration that the cookie is valid. |
secure_cookie |
bool |
No | false |
Whether to use secure cookies for access token (HTTPS only). Refresh token cookies are always secure. |
cookie_http_only |
bool |
No | false |
Whether to use HTTPOnly cookies. |
cookie_domain |
Option<String> |
No | None |
Domain for the cookie. |
cookie_name |
String |
No | "jwt" |
Name of the cookie. |
refresh_token_cookie_name |
String |
No | "refresh_token" |
Name of the refresh token cookie. |
cookie_same_site |
SameSite |
No | SameSite::Lax |
SameSite attribute for the cookie. |
send_authorization |
bool |
No | false |
Whether to return authorization header for every request. |
key_func |
Fn(&Header) -> Result<DecodingKey, JwtError> |
No | None |
Dynamic key function for multi-provider JWT support. |
skipper |
Fn(&ServiceRequest) -> bool |
No | None |
Skip middleware for matching requests. |
before_func |
Fn(&ServiceRequest) |
No | None |
Hook called before token extraction. |
success_handler |
Fn(&HttpRequest) -> Result<(), JwtError> |
No | None |
Hook called after successful token validation. |
error_handler |
Fn(&HttpRequest, JwtError) -> Option<JwtError> |
No | None |
Custom error handler; return None to ignore the error. |
continue_on_ignored_error |
bool |
No | false |
Continue to next handler when error_handler returns None. |
JWT Parsing Options
The jsonwebtoken crate's Validation struct controls JWT parsing behavior. While the middleware configures sensible defaults internally, you can customize validation by using key_func or by modifying the middleware source.
Clock Skew Tolerance (Leeway)
When running distributed systems across multiple servers, clock synchronization issues can cause valid tokens to be rejected. The jsonwebtoken crate supports leeway via Validation::leeway:
When to Use Leeway
- Microservices Architecture: Services on different machines with slightly unsynchronized clocks
- Cloud Deployments: Distributed systems across different availability zones or regions
- Load Balanced Environments: Multiple backend servers with small time drift
- Testing Environments: Development/staging systems with less strict time synchronization
How Leeway Works
With a 60-second leeway configuration:
- Expired tokens: A token that expired 30 seconds ago will still be accepted
- Not-before tokens: A token with
nbf30 seconds in the future will be accepted
Security Note: Use reasonable leeway values (30-120 seconds). Excessive leeway reduces token security by extending validity beyond intended expiration times.
Validation Example
use Validation;
let mut validation = new;
validation.leeway = 60; // 60 seconds clock skew tolerance
validation.validate_exp = true;
Other Parsing Options
Required Claims Validation
Enforce that certain claims must be present in the token:
let mut validation = new;
validation.set_required_spec_claims;
Audience Validation
let mut validation = new;
validation.set_audience;
Combining Multiple Options
let mut validation = new;
validation.leeway = 60; // 60s clock skew tolerance
validation.set_required_spec_claims; // Require expiration and subject
validation.set_audience; // Validate audience
Supporting Multiple JWT Providers
In some scenarios, you may need to accept JWT tokens from multiple sources, such as your own authentication system and external identity providers like Azure AD, Auth0, or other OAuth 2.0 providers. This section explains how to implement multi-provider token validation using the key_func callback.
Use Cases
- Hybrid Authentication: Support both internal and external authentication
- Third-Party Integration: Accept tokens from Azure AD, Google, Auth0, etc.
- Migration Scenarios: Gradually migrate from one auth system to another
- Enterprise SSO: Support enterprise Single Sign-On alongside regular auth
Solution: Dynamic Key Function
The recommended approach is to use a single middleware with a dynamic key_func that determines the appropriate validation method based on token properties (such as the issuer claim).
Why This Works
The key_func callback is designed for exactly this purpose. It allows you to:
- Inspect the token header before validation
- Choose the correct signing key/method dynamically
- Avoid issues when chaining multiple middlewares
Implementation
use Arc;
use ;
use ;
let own_secret = b"your-secret-key";
let mut jwt = new;
jwt.key = own_secret.to_vec;
jwt.identity_key = "sub".to_string;
// Dynamic key function - the core of multi-provider support
jwt.key_func = Some;
Provider-Specific Identity Handler
use HttpRequest;
use extract_claims;
use json;
jwt.identity_handler = new;
Provider-Specific Authorization
jwt.authorizer = new;
Key Considerations
- Token Issuer Validation: Always validate the
issclaim to ensure tokens are from trusted sources - Audience Validation: Verify the
audclaim matches your application's client ID - Algorithm Validation: Ensure the signing algorithm matches expectations (HS256 for your tokens, RS256 for Azure AD)
- Key Caching: Cache public keys from JWKS endpoints to reduce latency
- Key Rotation: Implement automatic key refresh to handle provider key rotation
- Error Handling: Provide clear error messages indicating which provider validation failed
- Security: Never skip signature validation or disable security checks
Testing Multi-Provider Setup
# Test with your own token
# Test with Azure AD token
Additional Resources
- Azure AD Token Validation
- JWKS (JSON Web Key Sets)
- RFC 7517 - JSON Web Key (JWK)
- jsonwebtoken crate for JWT handling in Rust
Token Generator (Direct Token Creation)
The token_generator functionality allows you to create JWT tokens directly without HTTP middleware, perfect for programmatic authentication, testing, and custom flows.
Basic Usage
use HashMap;
use Arc;
use Duration;
use ;
use json;
async
Token Structure
The token_generator method returns a structured Token:
Refresh Token Management
Use token_generator_with_revocation to refresh tokens and automatically revoke old ones:
// Refresh with automatic revocation of old token
let new_token = jwt.token_generator_with_revocation.await?;
// Old refresh token is now invalid
println!;
println!;
Use Cases:
- Programmatic Authentication: Service-to-service communication
- Testing: Generate tokens for testing authenticated endpoints
- Registration Flow: Issue tokens immediately after user signup
- Background Jobs: Create tokens for automated processes
- Custom Auth Flows: Build custom authentication logic
See the complete example for more details.
Redis Store Configuration
This library supports Redis as a backend for refresh token storage, feature-gated behind redis-store. Redis store provides better scalability and persistence compared to the default in-memory store.
Redis Features
- Automatic fallback to in-memory store if Redis connection fails
- Easy configuration via
RedisConfig - Configurable key prefix for Redis keys
- Optional TLS support
Configuration Options
RedisConfig
| Option | Type | Default | Description |
|---|---|---|---|
addr |
String |
"redis://127.0.0.1:6379/" |
Redis connection URL |
password |
Option<String> |
None |
Redis password |
db |
i32 |
0 |
Redis database number |
pool_size |
u32 |
10 |
Connection pool size |
key_prefix |
String |
"actix-jwt:" |
Prefix for all Redis keys |
tls |
bool |
false |
Whether to use TLS |
Fallback Behavior
If Redis connection fails during initialization:
- The middleware logs an error message
- Automatically falls back to in-memory store
- Application continues to function normally
This ensures high availability and prevents application failures due to Redis connectivity issues.
Example with Redis
Enable the redis-store feature in Cargo.toml:
[]
= { = "https://github.com/LdDl/actix-jwt", = ["redis-store"] }
use Arc;
use Duration;
use ;
use RedisRefreshTokenStore;
use ;
use json;
async
Demo
Run the example server:
Install httpie for easy API testing.
Login
Refresh Token
Using RFC 6749 compliant refresh tokens (default behavior):
# First login to get refresh token
# Method 1: With cookies enabled (automatic - recommended for browsers)
# The refresh token cookie is automatically sent, no need to manually include it
# Method 2: Send refresh token in JSON body
# Method 3: Use refresh token from response via form data
Security Note: When send_cookie is enabled, refresh tokens are automatically stored in httpOnly cookies. Browser-based applications can simply call the refresh endpoint without manually including the token - it's handled automatically by the cookie mechanism.
Important: Query parameters are NOT supported for refresh tokens as they expose tokens in server logs, proxy logs, browser history, and Referer headers. Use cookies (recommended), JSON body, or form data instead.
Hello World
Login as admin/admin and call:
Response:
Authorization Example
Login as test/test and call:
Response:
Understanding the Authorizer
The authorizer callback is a crucial component for implementing role-based access control in your application. It determines whether an authenticated user has permission to access specific protected routes.
How Authorizer Works
The authorizer is called automatically during the JWT middleware processing for any route that uses .wrap(jwt_arc.middleware()). Here is the execution flow:
- Token Validation: JWT middleware validates the token
- Identity Extraction:
identity_handlerextracts user identity from token claims - Authorization Check:
authorizerdetermines if the user can access the resource - Route Access: If authorized, request proceeds; otherwise,
unauthorizedis called
Authorizer Function Signature
Fn
&HttpRequest: The actix-web request containing request information&Value: User identity data returned byidentity_handler- Returns
bool:truefor authorized access,falseto deny access
Basic Usage Examples
Example 1: Role-Based Authorization
jwt.authorizer = new;
Example 2: Path-Based Authorization
jwt.authorizer = new;
Example 3: Method and Path Based Authorization
jwt.authorizer = new;
Setting Up Different Authorization for Different Routes
Method 1: Multiple Middleware Instances
// Admin-only middleware
let mut admin_jwt = new;
// ... shared config ...
admin_jwt.authorizer = new;
admin_jwt.init.unwrap;
let admin_arc = new;
// Regular user middleware
let mut user_jwt = new;
// ... shared config ...
user_jwt.authorizer = new;
user_jwt.init.unwrap;
let user_arc = new;
// Route setup
new
.service
.service
Method 2: Single Authorizer with Path Logic
jwt.authorizer = new;
Advanced Authorization Patterns
Using Claims for Fine-Grained Control
use extract_claims;
jwt.authorizer = new;
Common Patterns and Best Practices
- Always validate the data type: Check that the
Valuecontains expected fields before accessing - Use claims for additional context: Access JWT claims using
extract_claims(&req) - Consider the request context: Use
req.path(),req.method(), etc. - Fail securely: Return
falseby default and explicitly allow access - Log authorization failures: Add logging for debugging authorization issues
Complete Example
See the authorization example for a complete implementation showing different authorization scenarios.
Logout
Login first, then call the logout endpoint with the JWT token:
# First login to get the JWT token
# Use the returned JWT token to logout (replace xxxxxxxxx with actual token)
Response:
The logout response demonstrates that JWT claims are accessible during logout through extract_claims(&req), allowing developers to access user information for logging, auditing, or cleanup purposes.
Cookie Token
To set the JWT in a cookie, use these options (see MDN docs):
jwt.send_cookie = true;
jwt.secure_cookie = false; // for non-HTTPS dev environments (access token only)
jwt.cookie_http_only = true; // JS can't modify
jwt.cookie_domain = Some;
jwt.cookie_name = "token".to_string; // default: "jwt"
jwt.refresh_token_cookie_name = "refresh_token".to_string; // default: "refresh_token"
jwt.token_lookup = "cookie:token".to_string;
jwt.cookie_same_site = Lax; // Lax, Strict, or None
Refresh Token Cookie Support
When send_cookie is enabled, the middleware automatically stores both access and refresh tokens as httpOnly cookies:
- Access Token Cookie: Stored with the name specified in
cookie_name(default:"jwt") - Refresh Token Cookie: Stored with the name specified in
refresh_token_cookie_name(default:"refresh_token")
The refresh token cookie:
- Uses the
refresh_token_timeoutduration (default: 30 days) - Is always set with
httpOnly: truefor security - Is always set with
secure: true(HTTPS only) regardless of thesecure_cookiesetting - Is automatically sent with refresh requests
- Is cleared on logout
Automatic Token Extraction: The refresh_handler automatically extracts refresh tokens from cookies, form data, query parameters, or JSON body, in that order. This means you don't need to manually include the refresh token when using cookie-based authentication - it's handled automatically.
Login request flow (using login_handler)
PROVIDED: login_handler
This is a provided method to be called on any login endpoint, which will trigger the flow described below.
REQUIRED: authenticator
This callback should verify the user credentials given the HttpRequest and raw body bytes (i.e. password matches hashed password for a given user email, and any other authentication logic). Then the authenticator should return a serde_json::Value that contains the user data that will be embedded in the JWT token. This might be something like an account id, role, is_verified, etc. After having successfully authenticated, the data returned from the authenticator is passed in as a parameter into the payload_func, which is used to embed the user identifiers mentioned above into the JWT token. If an error is returned, the unauthorized callback is used.
OPTIONAL: payload_func
This function is called after having successfully authenticated (logged in). It should take whatever was returned from authenticator and convert it into a HashMap<String, Value>. A typical use case of this function is for when authenticator returns a Value which holds the user identifiers, and those fields need to be extracted into a map. The map should include one element that is [identity_key (default "identity"): some_user_identity]. The elements of the map returned in payload_func will be embedded within the JWT token (as token claims). When users pass in their token on subsequent requests, you can get these claims back by using extract_claims.
Standard JWT Claims (RFC 7519): You can set standard JWT claims in payload_func for better interoperability:
sub(Subject) - The user identifier (e.g., user ID)iss(Issuer) - The issuer of the token (e.g., your app name)aud(Audience) - The intended audience (e.g., your API)nbf(Not Before) - Token is not valid before this timeiat(Issued At) - When the token was issuedjti(JWT ID) - Unique identifier for the token
Note: The exp (Expiration) and orig_iat claims are managed by the framework and cannot be overwritten.
jwt.payload_func = Some;
OPTIONAL: login_response
After having successfully authenticated with authenticator, created the JWT token using the identifiers from the map returned from payload_func, and set cookies if send_cookie is enabled, this function is called. This function receives the complete token information as a structured Token object and should return the appropriate HttpResponse.
Signature: Fn(&HttpRequest, &Token) -> HttpResponse
Subsequent requests on endpoints requiring jwt token (using middleware)
PROVIDED: middleware()
This returns an actix-web middleware (Transform) that should be used via .wrap() on any scope or resource that requires JWT authentication. This middleware will parse the request headers for the token if it exists, and check that the JWT token is valid (not expired, correct signature). Then it will call identity_handler followed by authorizer. If authorizer passes and all of the previous token validity checks passed, the middleware will continue the request. If any of these checks fail, the unauthorized function is used.
OPTIONAL: identity_handler
The default of this function is likely sufficient for your needs. The purpose of this function is to fetch the user identity from claims embedded within the JWT token, and pass this identity value to authorizer. This function assumes [identity_key: some_user_identity] is one of the attributes embedded within the claims of the JWT token (determined by payload_func).
OPTIONAL: authorizer
Given the user identity value (data parameter) and the HttpRequest, this function should check if the user is authorized to be reaching this endpoint (on the endpoints where the middleware applies). This function should likely use extract_claims to check if the user has the sufficient permissions to reach this endpoint, as opposed to hitting the database on every request. This function should return true if the user is authorized to continue through with the request, or false if they are not authorized (where unauthorized will be called).
Logout request flow (using logout_handler)
PROVIDED: logout_handler
This is a provided method to be called on any logout endpoint. The handler performs the following actions:
- Extracts JWT claims to make them available in
logout_response(for logging/auditing) - Attempts to revoke the refresh token from the server-side store if provided
- Clears authentication cookies if
send_cookieis enabled:- Access Token Cookie: Named according to
cookie_name - Refresh Token Cookie: Named according to
refresh_token_cookie_name
- Access Token Cookie: Named according to
- Calls
logout_responseto return the response
The logout handler tries to extract the refresh token from multiple sources (cookie, form, query, JSON body) to ensure it can be properly revoked.
OPTIONAL: logout_response
This function is called after logout processing is complete. It should return the appropriate HttpResponse to indicate logout success or failure. Since logout doesn't generate new tokens, this function only receives the HttpRequest. You can access JWT claims and user identity via extract_claims(&req) and get_identity(&req) for logging or auditing purposes.
Signature: Fn(&HttpRequest) -> HttpResponse
Refresh request flow (using refresh_handler)
PROVIDED: refresh_handler
This is a provided method to be called on any refresh token endpoint. The handler expects a refresh_token parameter (RFC 6749 compliant) from multiple sources and validates it against the server-side token store. The handler automatically extracts the refresh token from the following sources in order of priority:
- Cookie (most common for browser-based apps):
refresh_token_cookie_namecookie (default:"refresh_token") - POST Form:
refresh_tokenform field - JSON Body:
refresh_tokenfield in request body
Security Note: Query parameters are NOT supported for refresh tokens to prevent token leakage through server logs, proxy logs, browser history, and Referer headers. Only secure delivery methods are supported.
If the refresh token is valid and not expired, the handler will:
- Create a new access token and refresh token
- Revoke the old refresh token (token rotation)
- Set both tokens as cookies (if
send_cookieis enabled) - Pass the new tokens into
refresh_response
This follows OAuth 2.0 security best practices by rotating refresh tokens and supporting multiple secure delivery methods.
Cookie-Based Authentication: When using cookies (recommended for browser apps), the refresh token is automatically sent with the request, so you don't need to manually include it. Simply call the refresh endpoint and the middleware handles everything.
OPTIONAL: refresh_response
This function is called after successfully refreshing tokens. It receives the complete new token information as a structured Token object and should return an HttpResponse containing the new access_token, token_type, expires_in, and refresh_token fields, following RFC 6749 token response format. Note that when using cookies, the tokens are already set as httpOnly cookies before this function is called.
Signature: Fn(&HttpRequest, &Token) -> HttpResponse
Failures with logging in, bad tokens, or lacking privileges
OPTIONAL: unauthorized
On any error logging in, authorizing the user, or when there was no token or an invalid token passed in with the request, the following will happen. http_status_message_func is called which by default converts the error into a string. Finally the unauthorized callback will be called. This function should likely return an HttpResponse containing the HTTP error code and error message to the user.
Note: When a 401 Unauthorized response is returned, the middleware automatically adds a WWW-Authenticate header with the Bearer authentication scheme, as defined in RFC 6750 (OAuth 2.0 Bearer Token Usage), RFC 7235 (HTTP Authentication), and the MDN documentation:
WWW-Authenticate: Bearer realm="<your-realm>"
This header informs HTTP clients that Bearer token authentication is required, ensuring compatibility with standard HTTP authentication mechanisms.