Authentication (JWT)
10/30/24About 1 min
JWT Authentication System
JSON Web Token (JWT) is the core technology for implementing stateless authentication in our application. This document covers the design, workflow, security features, and usage of our JWT system.
The system consists of two parts:
- Token Generation: Issue a time-limited JWT containing user identity after successful login
- Token Validation: Verify the JWT in each protected API request and extract user information
JWT Structure & Claims
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Claims {
pub uid: i64, // User ID
pub token_id: i64, // Token unique ID for whitelist verification
pub username: String,
pub exp: i64, // Expiration timestamp
}token_idis a key security enhancement — it's linked to a record in thesys_white_jwttable for proactive token invalidation (logout).
Workflow
1. Token Generation (authorize function)
After successful login:
- Receive
AuthPayloadwith user info - Generate
token_idby inserting a record intosys_white_jwttable - Calculate expiration time (
exp) - Create
Claimsinstance - Sign with the global secret key (
KEYS.encoding) - Return
AuthBodywith token and expiration info
2. Token Validation (UserInfo extractor)
When a handler has user_info: UserInfo as a parameter, Axum automatically:
- Extracts Bearer Token from
Authorization: Bearer <token>header - Decodes and validates the token signature and expiration
- Checks if
token_idexists in the whitelist (allows proactive logout) - Re-queries user's latest info from the database (ensures role changes take effect immediately)
- Injects
UserInfointo request extensions
Security Design
Security Features
Balance of Stateless & Stateful:
- Traditional JWT is fully stateless — once issued, it cannot be revoked before expiry
- Our system introduces
token_idand a whitelist table for a "semi-stateful" mode
Real-time Role Changes:
- By re-querying user info on every request, permission changes take effect immediately
Centralized Key Management:
- All token signing/validation uses a global static
KEYSinitialized viaonce_cell::sync::Lazy
- All token signing/validation uses a global static
Clear Error Types (
AuthError):AuthErrorenum defines all authentication failure scenarios with precise HTTP status codes