sa-token-rust
中文文档 | English
A lightweight, high-performance authentication and authorization framework for Rust, inspired by sa-token.
✨ Features
- 🚀 Multiple Web Framework Support: Axum, Actix-web, Poem, Rocket, Warp, Salvo, Tide, Gotham, Ntex
- 🔐 Complete Authentication: Login, logout, token validation, session management
- 🛡️ Fine-grained Authorization: Permission and role-based access control
- 💾 Flexible Storage: Memory, Redis, and database storage backends
- 🎯 Easy to Use: Procedural macros and utility classes for simple integration
- ⚡ High Performance: Zero-copy design, async/await support
- 🔧 Highly Configurable: Token timeout, cookie options, custom token names
- 🎧 Event Listeners: Monitor login, logout, kick-out, and other authentication events
- 🔑 JWT Support: Full JWT (JSON Web Token) implementation with multiple algorithms
- 🔒 Security Features: Nonce for replay attack prevention, refresh token mechanism
- 🌐 OAuth2 Support: Complete OAuth2 authorization code flow implementation
- 🌐 WebSocket Authentication: Secure WebSocket connection authentication with multiple token sources
- 👥 Online User Management: Real-time online status tracking and message push
- 🔄 Distributed Session: Cross-service session sharing for microservices architecture
- 🎫 SSO Single Sign-On: Complete SSO implementation with ticket-based authentication and unified logout
📦 Architecture
sa-token-rust/
├── sa-token-core/ # Core library (Token, Session, Manager)
│ ├── token/ # Token management
│ │ ├── generator.rs # Token generation (UUID, Random, JWT, Hash, Timestamp, Tik)
│ │ ├── validator.rs # Token validation
│ │ ├── jwt.rs # JWT implementation (HS256/384/512, RS256/384/512, ES256/384)
│ │ └── mod.rs # Token types (TokenValue, TokenInfo)
│ ├── session/ # Session management
│ ├── permission/ # Permission and role checking
│ ├── event/ # Event listener system
│ │ └── mod.rs # Event bus, listeners (Login, Logout, KickOut, etc.)
│ ├── nonce.rs # Nonce manager (replay attack prevention)
│ ├── refresh.rs # Refresh token manager
│ ├── oauth2.rs # OAuth2 authorization code flow
│ ├── ws.rs # WebSocket authentication
│ ├── online.rs # Online user management and real-time push
│ ├── distributed.rs # Distributed session management
│ ├── sso.rs # SSO single sign-on (Server, Client, Ticket)
│ ├── manager.rs # SaTokenManager (core manager)
│ ├── config.rs # Configuration and builder
│ └── util.rs # StpUtil (utility class)
├── sa-token-adapter/ # Adapter interfaces (Storage, Request/Response)
├── sa-token-macro/ # Procedural macros (#[sa_check_login], etc.)
├── sa-token-storage-memory/ # Memory storage implementation
├── sa-token-storage-redis/ # Redis storage implementation
├── sa-token-storage-database/ # Database storage implementation (placeholder)
├── sa-token-plugin-axum/ # Axum framework integration
├── sa-token-plugin-actix-web/ # Actix-web framework integration
├── sa-token-plugin-poem/ # Poem framework integration
├── sa-token-plugin-rocket/ # Rocket framework integration
├── sa-token-plugin-warp/ # Warp framework integration
├── sa-token-plugin-salvo/ # Salvo framework integration
├── sa-token-plugin-tide/ # Tide framework integration
├── sa-token-plugin-gotham/ # Gotham framework integration
├── sa-token-plugin-ntex/ # Ntex framework integration
├── examples/ # Example projects
│ ├── event_listener_example.rs # Event listener demo
│ ├── jwt_example.rs # JWT complete demo
│ ├── token_styles_example.rs # Token styles demo
│ ├── security_features_example.rs # Nonce & Refresh token demo
│ ├── oauth2_example.rs # OAuth2 authorization flow demo
│ ├── websocket_online_example.rs # WebSocket auth & online user demo
│ ├── distributed_session_example.rs # Distributed session demo
│ └── sso_example.rs # SSO single sign-on demo
└── docs/ # Documentation
├── JWT_GUIDE.md / JWT_GUIDE_zh-CN.md
├── OAUTH2_GUIDE.md / OAUTH2_GUIDE_zh-CN.md
├── EVENT_LISTENER.md / EVENT_LISTENER_zh-CN.md
├── WEBSOCKET_AUTH.md # WebSocket authentication (7 languages)
├── ONLINE_USER_MANAGEMENT.md # Online user management (7 languages)
├── DISTRIBUTED_SESSION.md # Distributed session (7 languages)
├── ERROR_REFERENCE.md # Error reference (7 languages)
└── StpUtil.md / StpUtil_zh-CN.md
🎯 Core Components
1. sa-token-core
Core authentication and authorization logic:
SaTokenManager: Main manager for token and session operationsStpUtil: Utility class providing simplified API (Documentation)- Token generation, validation, and refresh
- Multiple token styles (UUID, Random, JWT, Hash, Timestamp, Tik)
- Session management
- Permission and role checking
- Event listening system (Documentation)
- JWT support with multiple algorithms (JWT Guide)
- Security features: Nonce (replay attack prevention), Refresh Token
- OAuth2 authorization code flow (OAuth2 Guide)
- WebSocket authentication (WebSocket Guide)
- Online user management and real-time push (Online User Guide)
- Distributed session for microservices (Distributed Session Guide)
- SSO single sign-on (SSO Guide)
2. sa-token-adapter
Abstraction layer for framework integration:
SaStorage: Storage interface for tokens and sessionsSaRequest/SaResponse: Request/response abstraction
3. sa-token-macro
Procedural macros for annotation-style authentication:
#[sa_check_login]: Require login#[sa_check_permission("user:list")]: Check permission (Matching Rules)#[sa_check_role("admin")]: Check role#[sa_check_permissions_and(...)]: Check multiple permissions (AND)#[sa_check_permissions_or(...)]: Check multiple permissions (OR)#[sa_ignore]: Skip authentication
4. Web Framework Plugins
Supported frameworks: Axum, Actix-web, Poem, Rocket, Warp, Salvo, Tide, Gotham, Ntex
All plugins provide:
- State management with Builder pattern
- Dual middleware (basic + login-required)
- Three extractors (required, optional, LoginId)
- Request/Response adapters
- Token extraction from Header/Cookie/Query
- Bearer token support
🚀 Quick Start
⚡ Simplified Usage (Recommended)
New! Import everything you need with a single dependency:
[]
# All-in-one package - includes core, macros, and storage
= "0.1.4" # Default: memory storage
= { = "1", = ["full"] }
= "0.8"
One-line import:
use *; // ✨ Everything you need!
// Now you can use:
// - SaTokenManager, StpUtil
// - MemoryStorage, RedisStorage (with features)
// - All macros: #[sa_check_login], #[sa_check_permission]
// - JWT, OAuth2, WebSocket, Online users, etc.
Choose your storage backend with features:
# Redis storage
= { = "0.1.4", = ["redis"] }
# Multiple storage backends
= { = "0.1.4", = ["memory", "redis"] }
# All storage backends
= { = "0.1.4", = ["full"] }
Available features:
memory(default): In-memory storageredis: Redis storagedatabase: Database storagefull: All storage backends
Available plugins:
sa-token-plugin-axum- Axum frameworksa-token-plugin-actix-web- Actix-web frameworksa-token-plugin-poem- Poem frameworksa-token-plugin-rocket- Rocket frameworksa-token-plugin-warp- Warp framework
📦 Traditional Usage (Advanced)
If you prefer fine-grained control, you can still import packages separately:
[]
= "0.1.4"
= "0.1.4"
= "0.1.4"
= { = "1", = ["full"] }
= "0.8"
2. Initialize sa-token
Option A: Using Memory Storage (Development)
With simplified import:
use *; // ✨ One-line import
use Arc;
async
Option B: Using Redis Storage (Production)
Add Redis feature to your dependency:
[]
= { = "0.1.4", = ["redis"] }
With simplified import:
use *; // ✨ RedisStorage already included!
use Arc;
async
Method 2: RedisConfig Structure (Recommended for configuration files)
use ;
use SaTokenState;
use Arc;
async
Method 3: Builder Pattern (Most flexible)
use RedisStorage;
use SaTokenState;
use Arc;
async
3. User Login
use StpUtil;
// User login
let token = login.await?;
println!;
// Set permissions and roles
set_permissions.await?;
set_roles.await?;
4. Check Authentication (Axum Example)
use ;
use ;
async
async
let app = new
.route
.route
.layer;
5. Using Procedural Macros
use *;
async
async
async
6. Event Listeners
Monitor authentication events like login, logout, and kick-out:
use async_trait;
use SaTokenListener;
use Arc;
// Create custom listener
;
// Register listener
register_listener.await;
// Or use built-in logging listener
use LoggingListener;
register_listener.await;
// Events are automatically triggered
let token = login.await?; // Triggers Login event
logout.await?; // Triggers Logout event
kick_out.await?; // Triggers KickOut event
For complete event listener documentation, see Event Listener Guide.
7. Token Styles
sa-token-rust supports multiple token generation styles to meet different scenarios:
use SaTokenConfig;
use TokenStyle;
let config = builder
.token_style // Choose your preferred style
.build_config;
Available Token Styles
| Style | Length | Example | Use Case |
|---|---|---|---|
| Uuid | 36 chars | 550e8400-e29b-41d4-a716-446655440000 |
Standard UUID format, universally recognized |
| SimpleUuid | 32 chars | 550e8400e29b41d4a716446655440000 |
UUID without hyphens, more compact |
| Random32 | 32 chars | a3f5c9d8e2b7f4a6c1e8d3b9f2a7c5e1 |
Random hex string, good security |
| Random64 | 64 chars | a3f5c9d8... |
Longer random string, higher security |
| Random128 | 128 chars | a3f5c9d8... |
Maximum random length, ultra-secure |
| Jwt | Variable | eyJhbGc... |
Self-contained token with claims (JWT Guide) |
| Hash ⭐ | 64 chars | 472c7dce... |
SHA256 hash with user info, traceable |
| Timestamp ⭐ | ~30 chars | 1760404107094_a8f4f17d88fcddb8 |
Includes timestamp, easy to track |
| Tik ⭐ | 8 chars | GIxYHHD5 |
Short and shareable, perfect for URLs |
⭐ = New in this version
Token Style Examples
// Uuid style (default)
.token_style
// Output: 550e8400-e29b-41d4-a716-446655440000
// Hash style - includes user information in hash
.token_style
// Output: 472c7dceee2b3079a1ae70746f43ba99b91636292ba7811b3bc8985a1148836f
// Timestamp style - includes millisecond timestamp
.token_style
// Output: 1760404107094_a8f4f17d88fcddb8
// Tik style - short 8-character token
.token_style
// Output: GIxYHHD5
// JWT style - self-contained token with claims
.token_style
.jwt_secret_key
// Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Choosing the Right Token Style
- Uuid/SimpleUuid: Standard choice, widely compatible
- Random32/64/128: When you need random tokens with specific length
- JWT: When you need self-contained tokens with embedded information
- Hash: When you need tokens that can be traced back to user info
- Timestamp: When you need to know when the token was created
- Tik: When you need short tokens for sharing (URLs, QR codes, etc.)
Run the example to see all token styles in action:
8. Security Features
Nonce (Replay Attack Prevention)
use NonceManager;
let nonce_manager = new; // 5 minutes TTL
// Generate nonce
let nonce = nonce_manager.generate;
// Validate and consume (one-time use)
nonce_manager.validate_and_consume.await?;
// Second use will fail (replay attack detected)
match nonce_manager.validate_and_consume.await
Refresh Token
use RefreshTokenManager;
let refresh_manager = new;
// Generate refresh token
let refresh_token = refresh_manager.generate;
refresh_manager.store.await?;
// Refresh access token when expired
let = refresh_manager
.refresh_access_token
.await?;
Run security features example:
9. OAuth2 Authorization
Complete OAuth2 authorization code flow implementation:
use ;
let oauth2 = new;
// Register OAuth2 client
let client = OAuth2Client ;
oauth2.register_client.await?;
// Generate authorization code
let auth_code = oauth2.generate_authorization_code;
oauth2.store_authorization_code.await?;
// Exchange code for token
let token = oauth2.exchange_code_for_token.await?;
// Verify access token
let token_info = oauth2.verify_access_token.await?;
// Refresh token
let new_token = oauth2.refresh_access_token.await?;
Run OAuth2 example:
10. SSO Single Sign-On
Complete SSO implementation with ticket-based authentication:
use ;
// Create SSO Server
let sso_server = new
.with_ticket_timeout; // 5 minutes
// Create SSO Client
let client = new;
// Configure SSO with cross-domain support
let config = builder
.server_url
.ticket_timeout
.allow_cross_domain
.add_allowed_origin
.build;
// User login flow
let ticket = sso_server.login.await?;
// Validate ticket
let login_id = sso_server.validate_ticket.await?;
// Create local session
let token = client.login_by_ticket.await?;
// Unified logout (all applications)
let clients = sso_server.logout.await?;
for client_url in clients
Run SSO example:
📖 Full Event Listener Documentation
📚 Framework Integration Examples
Axum
use ;
use ;
let state = builder
.storage
.build;
let app = new
.route
.layer;
Actix-web
use ;
use ;
let state = builder
.storage
.build;
new
.bind?
.run
.await
Poem
use ;
use ;
let state = builder
.storage
.build;
let app = new
.at
.with;
new
.run
.await
Rocket
use ;
use ;
Warp
use Filter;
use ;
let state = builder
.storage
.build;
let routes = path
.and
.and
.map;
serve
.run
.await;
📖 Documentation
Core Documentation
- StpUtil API Reference - Complete guide to StpUtil utility class
- Permission Matching Rules - How permission checking works
- Architecture Overview - System architecture and design
- Quick Start Guide - Get started quickly
Feature Guides
-
Authentication & Authorization
- Event Listener Guide - Monitor authentication events (Login, Logout, KickOut)
- JWT Guide - JSON Web Token implementation with 8 algorithms
- OAuth2 Guide - OAuth2 authorization code flow
-
Real-time & WebSocket
- WebSocket Authentication - Secure WebSocket connection auth (7 languages)
- Online User Management - Real-time status tracking and push (7 languages)
-
Distributed Systems
- Distributed Session - Cross-service session sharing (7 languages)
- SSO Single Sign-On - Ticket-based SSO with unified logout (7 languages)
-
Error Handling
- Error Reference - Complete error types documentation (7 languages)
Examples
- Examples Directory - Working examples for all features
event_listener_example.rs- Event listener with WebSocket supportjwt_example.rs- JWT generation and validationtoken_styles_example.rs- 7 token generation stylessecurity_features_example.rs- Nonce & Refresh Tokenoauth2_example.rs- OAuth2 authorization flowwebsocket_online_example.rs- WebSocket auth & online user managementdistributed_session_example.rs- Distributed session managementsso_example.rs- SSO single sign-on with ticket validation
Language Support
Most documentation is available in 7 languages:
- 🇬🇧 English
- 🇨🇳 中文 (Chinese)
- 🇹🇭 ภาษาไทย (Thai)
- 🇻🇳 Tiếng Việt (Vietnamese)
- 🇰🇭 ភាសាខ្មែរ (Khmer)
- 🇲🇾 Bahasa Melayu (Malay)
- 🇲🇲 မြန်မာဘာသာ (Burmese)
📋 Version History
Version 0.1.4 (Current)
New Features:
- 🎫 SSO Single Sign-On: Complete SSO implementation with ticket-based authentication
- SSO Server for centralized authentication
- SSO Client for application integration
- Ticket generation, validation, and expiration
- Unified logout across all applications
- Cross-domain support with origin whitelist
- Service URL matching for security
- 🔧 Enhanced Universal Adapter: Common utility functions for framework integration
parse_cookies(): Parse HTTP Cookie headersparse_query_string(): Parse URL query parameters with auto URL decodingbuild_cookie_string(): Build Set-Cookie header stringsextract_bearer_token(): Extract Bearer token from Authorization header- Complete unit tests and bilingual documentation
- 🚀 4 New Framework Support: Expanded framework ecosystem
- Salvo (v0.73): Modern web framework with Handler macros
- Request/Response adapter
- Authentication and permission middleware
- Tide (v0.16): async-std based framework
- Request/Response adapter
- Middleware with extension data support
- Gotham (v0.7): Type-safe routing framework
- Simplified middleware (due to complex State system)
- Ntex (v2.8): High-performance framework
- Complete middleware with Service trait
- Salvo (v0.73): Modern web framework with Handler macros
Improvements:
- Reduced code duplication by 70% with common utilities
- Unified interface design across all 9 frameworks
- Better type safety with TokenValue conversions
- Improved error handling for each framework
- Framework support expanded from 5 to 9 (+80%)
Version 0.1.3
New Features:
- 🌐 WebSocket Authentication: Secure WebSocket connection authentication
- Multiple token sources (header, query, custom)
- WsAuthManager for connection management
- Integration with event system
- 👥 Online User Management: Real-time user status tracking
- OnlineManager for tracking active users
- Message push to online users
- Custom message types support
- 🔄 Distributed Session: Cross-service session sharing
- Service-to-service authentication
- Distributed session storage
- Service credential management
- 🎨 Enhanced Event System: Improved event listener registration
- Builder pattern integration for event listeners
- Synchronous registration (no
.awaitneeded) - Automatic StpUtil initialization
- 📚 Documentation Improvements:
- 7-language support for major features
- Multi-language merged documentation format
- Comprehensive code comments (bilingual)
- Code flow logic documentation
Improvements:
- Simplified import with plugin re-exports
- One-line initialization via builder pattern
- Better error handling with centralized error definitions
- Enhanced API documentation
Version 0.1.2
New Features:
- 🔑 JWT Support: Full JWT implementation
- 8 algorithms (HS256/384/512, RS256/384/512, ES256/384)
- Custom claims support
- Token refresh mechanism
- 🔒 Security Features:
- Nonce manager for replay attack prevention
- Refresh token mechanism
- 🌐 OAuth2 Support: Complete OAuth2 authorization code flow
- Client registration and management
- Authorization code generation and exchange
- Access token and refresh token handling
- Token revocation
- 🎨 New Token Styles: Hash, Timestamp, Tik styles
- 🎧 Event Listener System: Monitor authentication events
- Login, Logout, KickOut events
- Custom listener support
- Built-in LoggingListener
Improvements:
- Error handling refactored to use centralized
SaTokenError - Multi-language error documentation
- Enhanced permission and role checking
Version 0.1.1
New Features:
- 🚀 Multi-framework Support: Axum, Actix-web, Poem, Rocket, Warp
- 🔐 Core Authentication: Login, logout, token validation
- 🛡️ Authorization: Permission and role-based access control
- 💾 Storage Backends: Memory and Redis storage
- 🎯 Procedural Macros:
#[sa_check_login],#[sa_check_permission],#[sa_check_role] - 📦 Flexible Architecture: Core library with framework adapters
Core Components:
SaTokenManager: Token and session managementStpUtil: Simplified utility API- Multiple token generation styles (UUID, Random32/64/128)
- Session management
- Storage abstraction layer
🔧 Advanced Usage
Custom Storage
Implement the SaStorage trait for your own storage backend:
use SaStorage;
use async_trait;
;
Token Configuration
let state = builder
.storage
.token_name // Custom token name
.timeout // Token timeout (seconds)
.active_timeout // Activity timeout (seconds)
.build;
🤝 Contributing
Contributions are welcome! Please feel free to submit issues and pull requests.
📄 License
This project is licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT License (LICENSE-MIT)
at your option.
👨💻 Author
金书记
🙏 Acknowledgments
This project is inspired by sa-token Java framework.