sa-token-core
Core authentication and authorization library for sa-token-rust.
Features
- ๐ Token Management: Generate, validate, and refresh tokens
- ๐จ Multiple Token Styles: UUID, Random, JWT, Hash, Timestamp, Tik
- ๐ค Session Management: User session storage and management
- ๐ก๏ธ Permission Control: Role and permission-based access control
- โฐ Timeout Control: Flexible token and session timeout configuration
- ๐ JWT Support: Full JWT implementation with 8 algorithms (HS256/384/512, RS256/384/512, ES256/384)
- ๐ง Event System: Listen to login, logout, kick-out, and other authentication events
- ๐ Security Features: Nonce for replay attack prevention, Refresh Token mechanism
- ๐ OAuth2: Complete OAuth2 authorization code flow implementation
- ๐ Multi-language Error Docs: Error documentation in 7 languages
Installation
[]
= "0.1.10"
= "0.1.10"
= { = "1", = ["full"] }
Quick Start
Basic Authentication
use ;
use Arc;
// Create configuration
let config = default
.with_timeout // 2 hours
.with_token_name;
// Create manager
let manager = new;
// Login
let token = manager.login.await?;
// Validate token
let is_valid = manager.is_valid.await?;
// Logout
manager.logout.await?;
JWT Authentication
use ;
// Configure JWT
let config = default
.with_token_style
.with_jwt_secret_key
.with_jwt_algorithm;
// Or use JWT directly
let jwt = new;
let token = jwt.generate?;
let claims = jwt.validate?;
Event Listeners
use ;
use async_trait;
;
// Register listener
manager.event_bus.register.await;
OAuth2 Authorization
use ;
let oauth2 = new;
// Register client
let client = OAuth2Client ;
oauth2.register_client.await?;
// Authorization flow
let auth_code = oauth2.generate_authorization_code;
let token = oauth2.exchange_code_for_token.await?;
Security Features
use ;
// Nonce for replay attack prevention
let nonce_mgr = new;
let nonce = nonce_mgr.generate;
nonce_mgr.validate_and_consume.await?;
// Refresh token
let refresh_mgr = new;
let refresh_token = refresh_mgr.generate;
let = refresh_mgr.refresh_access_token.await?;
Core Components
SaTokenManager
Main manager for token and session operations with event support.
// Create token
let token = manager.login.await?;
// Check login status
let is_login = manager.is_login.await?;
// Get login ID
let login_id = manager.get_login_id.await?;
// Access event bus
let event_bus = manager.event_bus;
event_bus.register.await;
// Logout (triggers event)
manager.logout.await?;
Token Styles
Support for 7 different token generation styles:
use TokenStyle;
// UUID (default)
config.with_token_style;
// Output: 550e8400-e29b-41d4-a716-446655440000
// Simple UUID (no hyphens)
config.with_token_style;
// Output: 550e8400e29b41d4a716446655440000
// Random (32, 64, or 128 chars)
config.with_token_style;
// Output: a1b2c3d4e5f6...
// JWT
config.with_token_style;
// Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
// Hash (SHA256 of login_id + timestamp)
config.with_token_style;
// Output: 5f4dcc3b5aa765d61d8327deb882cf99
// Timestamp
config.with_token_style;
// Output: 1728876543_a1b2c3d4
// Tik (short alphanumeric)
config.with_token_style;
// Output: aB3dE9fG2h
JWT Manager
Full JWT implementation with multiple algorithms:
use ;
let jwt = new;
// Generate JWT
let token = jwt.generate?; // 1 hour
// Validate JWT
let claims = jwt.validate?;
println!;
// Refresh JWT
let new_token = jwt.refresh?;
// Custom claims
let mut custom_claims = new;
custom_claims.add_custom;
let token = jwt.generate_with_claims?;
Event System
Monitor authentication events:
use ;
use async_trait;
;
// Register listener
manager.event_bus.register.await;
Nonce Manager
Prevent replay attacks:
use NonceManager;
let nonce_mgr = new; // 5 minutes
// Generate unique nonce
let nonce = nonce_mgr.generate;
// Output: nonce_1728876543000_a1b2c3d4e5f6
// Validate and consume (one-time use)
nonce_mgr.validate_and_consume.await?;
// Second use fails (replay attack detected)
match nonce_mgr.validate_and_consume.await
Refresh Token Manager
Token refresh mechanism:
use RefreshTokenManager;
let refresh_mgr = new;
// Generate refresh token
let refresh_token = refresh_mgr.generate;
refresh_mgr.store.await?;
// Refresh access token when expired
let = refresh_mgr
.refresh_access_token
.await?;
// Validate refresh token
let login_id = refresh_mgr.validate.await?;
// Delete refresh token
refresh_mgr.delete.await?;
OAuth2 Manager
Complete OAuth2 authorization code flow:
use ;
let oauth2 = new
.with_ttl; // code, access, refresh TTL
// Register OAuth2 client
let client = OAuth2Client ;
oauth2.register_client.await?;
// Authorization code flow
let auth_code = oauth2.generate_authorization_code;
oauth2.store_authorization_code.await?;
// Exchange code for tokens
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?;
// Revoke token
oauth2.revoke_token.await?;
Configuration
Basic Configuration
use ;
let config = default
.with_token_name
.with_timeout // 2 hours
.with_is_concurrent // Single device login
.with_is_share // No session sharing
.with_token_style
.with_is_log; // Enable logging
JWT Configuration
let config = default
.with_token_style
.with_jwt_secret_key
.with_jwt_algorithm
.with_jwt_issuer
.with_jwt_audience;
Security Configuration
let config = default
// Enable Nonce
.with_enable_nonce
.with_nonce_timeout // 5 minutes
// Enable Refresh Token
.with_enable_refresh_token
.with_refresh_token_timeout; // 30 days
Architecture
sa-token-core/
โโโ config.rs # Configuration and builder
โโโ manager.rs # SaTokenManager (core manager with event support)
โโโ util.rs # StpUtil (utility class for simplified API)
โโโ error.rs # Error definitions (32 types in 10 categories)
โโโ session/ # Session management
โโโ permission/ # Permission and role control
โโโ event/ # Event system (bus, listeners, event types)
โโโ token/ # Token management
โ โโโ generator.rs # Token generation (7 styles)
โ โโโ validator.rs # Token validation
โ โโโ jwt.rs # JWT implementation (8 algorithms)
โ โโโ mod.rs # Token types
โโโ nonce.rs # Nonce manager (replay attack prevention)
โโโ refresh.rs # Refresh token manager
โโโ oauth2.rs # OAuth2 authorization code flow
Error Handling
All errors are defined in error.rs with 32 types across 10 categories:
use SaTokenError;
match manager.login.await
See Error Reference for complete error documentation in 7 languages:
- English
- ไธญๆ (Chinese)
- เธ เธฒเธฉเธฒเนเธเธข (Thai)
- Tiแบฟng Viแปt (Vietnamese)
- แแถแแถแแแแแ (Khmer)
- Bahasa Melayu (Malay)
- แแผแแบแแฌแแฌแแฌ (Burmese)
Examples
Run the examples to see features in action:
# Event listeners
# JWT authentication
# Token styles (all 7 styles)
# Security features (Nonce + Refresh Token)
# OAuth2 authorization flow
Token Styles Reference
| Style | Format | Use Case | Example |
|---|---|---|---|
| Uuid | Standard UUID | Default, widely compatible | 550e8400-e29b-41d4-a716-446655440000 |
| SimpleUuid | UUID without hyphens | Compact format | 550e8400e29b41d4a716446655440000 |
| Random32 | 32 random chars | Short tokens | a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6 |
| Random64 | 64 random chars | Medium tokens | a1b2c3d4... (64 chars) |
| Random128 | 128 random chars | Long tokens | a1b2c3d4... (128 chars) |
| Jwt | JSON Web Token | Self-contained | eyJhbGciOiJIUzI1NiIsInR5cCI... |
| Hash | SHA256 hash | Traceable to user | 5f4dcc3b5aa765d61d8327deb882cf99 |
| Timestamp | Timestamp + random | Time-aware | 1728876543_a1b2c3d4 |
| Tik | Short alphanumeric | URL/QR friendly | aB3dE9fG2h |
Security Features
Nonce (Replay Attack Prevention)
Prevents duplicate requests and replay attacks:
- One-time use nonces
- Timestamp-based validation
- Configurable time window
- Automatic expiration
let nonce_mgr = new;
let nonce = nonce_mgr.generate;
nonce_mgr.validate_and_consume.await?;
Refresh Token
Long-lived tokens for refreshing access tokens:
- Separate refresh token lifecycle
- Secure refresh flow
- Automatic cleanup
- Configurable TTL (default 30 days)
let refresh_mgr = new;
let refresh_token = refresh_mgr.generate;
let = refresh_mgr
.refresh_access_token.await?;
OAuth2 Authorization
Complete OAuth2 authorization code flow:
- Client registration and verification
- Authorization code generation (10 min TTL)
- Access token issuance (1 hour TTL)
- Refresh token support (30 days TTL)
- Redirect URI validation
- Scope permission control
- Token revocation
let oauth2 = new;
oauth2.register_client.await?;
let auth_code = oauth2.generate_authorization_code;
let token = oauth2.exchange_code_for_token.await?;
Performance
- Async/await: Non-blocking I/O operations
- Zero-copy: Minimal memory allocations
- Concurrent: Thread-safe with Arc and RwLock
- Efficient: Storage-level TTL for automatic cleanup
Testing
Run all tests:
Run specific test module:
Documentation
Core Guides
- Architecture
- Quick Start
- Error Reference - 7 languages
Feature Guides
Author
้ไนฆ่ฎฐ
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT License (LICENSE-MIT)
at your option.