toolcraft-jwt
A lightweight JWT (JSON Web Token) library for Rust with support for access and refresh tokens.
Features
- 🔐 Access and refresh token generation
- ✅ Token validation with configurable rules
- ⏱️ Customizable token expiration times
- 🔄 Refresh token rotation support
- 🎯 Type-safe error handling
- 🚀 Simple and intuitive API
Installation
Add this to your Cargo.toml:
[]
= "*"
Check the crates.io page for the latest version.
Quick Start
use ;
Advanced Usage
Token Generation
// Generate only access token
let access_token = jwt.generate_access_token?;
// Generate token pair
let = jwt.generate_token_pair?;
Token Validation
// Validate access token
let claims = jwt.validate_access_token?;
println!;
println!;
println!;
println!;
// Validate refresh token
let claims = jwt.validate_refresh_token?;
Token Refresh
// Use refresh token to get new access token
let new_access_token = jwt.refresh_access_token?;
Custom Configuration
use JwtCfg;
let config = JwtCfg ;
Error Handling
use Error;
match jwt.validate_access_token
API Reference
JwtCfg
Configuration struct for JWT settings:
access_secret: Secret key for access tokensrefresh_secret: Secret key for refresh tokensaudience: Expected audience claimaccess_token_duration: Access token lifetime in secondsrefresh_token_duration: Refresh token lifetime in secondsaccess_key_validate_exp: Whether to validate access token expirationrefresh_key_validate_exp: Whether to validate refresh token expiration
Jwt Methods
new(cfg: JwtCfg)- Create a new JWT instancegenerate_token_pair(sub: String)- Generate access and refresh tokensgenerate_access_token(sub: String)- Generate only access tokenvalidate_access_token(token: &str)- Validate access tokenvalidate_refresh_token(token: &str)- Validate refresh tokenrefresh_access_token(refresh_token: &str)- Generate new access token from refresh token
Claims
JWT claims structure:
aud: Audiencesub: Subject (typically user ID)exp: Expiration time (Unix timestamp)iat: Issued at time (Unix timestamp)
Security Considerations
- Secret Keys: Use strong, randomly generated secret keys for production
- Key Rotation: Regularly rotate your secret keys
- HTTPS Only: Always transmit tokens over HTTPS
- Storage: Never store tokens in localStorage; use httpOnly cookies when possible
- Expiration: Use short expiration times for access tokens
License
This project is licensed under the MIT License - see the LICENSE file for details.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.