# jwt-lab
[](https://crates.io/crates/jwt-lab)
[](https://docs.rs/jwt-lab)
[](https://github.com/yourname/jwt-lab#license)
JWT crate for Rust. Decode, verify, sign, mutate, select keys from JWKS by kid, validate times with leeway, and choose algorithms with feature flags.
## Features
- **Multiple Algorithms**: HS256/384/512, RS256/384/512, ES256/384/512, EdDSA
- **JWK/JWKS Support**: Verify tokens using JSON Web Key Sets
- **Algorithm Validation**: Prevent algorithm confusion attacks
- **Time Validation**: Configurable leeway for `exp` and `nbf` claims
- **Claims Mutation**: Modify JWT claims using JSON pointer paths
- **Feature Flags**: Fine-grained control over included algorithms
- **Strong Error Types**: Comprehensive error handling with clear messages
## Usage
Add to your `Cargo.toml`:
```toml
[dependencies]
jwt-lab = "0.1"
```
### Basic Usage
```rust
use jwt_lab::{Jwt, Key, VerifyOptions, Algorithm};
// Decode and verify a JWT
let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...";
let jwt = Jwt::decode(token)?;
// Always validate the algorithm to prevent alg confusion attacks
jwt.verify(
&Key::hs("secret"),
VerifyOptions::default()
.expect_alg(Algorithm::HS256)
.leeway(30)
)?;
```
### JWKS Verification
```rust
use jwt_lab::{Jwt, Jwks, VerifyOptions};
let jwks = Jwks::from_str(&std::fs::read_to_string("jwks.json")?)?;
let jwt = Jwt::decode(token)?;
jwt.verify_with_jwks(&jwks, VerifyOptions::default())?;
```
### Signing Tokens
```rust
use jwt_lab::{Algorithm, Header, Claims, Key};
use jwt_lab::sign::sign;
use serde_json::json;
let header = Header {
alg: Algorithm::HS256,
typ: Some("JWT".into()),
kid: None,
extra: Default::default()
};
let claims = Claims(serde_json::from_value(json!({
"sub": "user123",
"iat": 1516239022,
"exp": 1516242622
}))?);
let token = sign(&header, &claims, &Key::hs("secret"))?;
```
## Security Considerations
⚠️ **Important Security Notes:**
- **Always validate the algorithm** to prevent algorithm confusion attacks
- **Never accept tokens with `alg: "none"`**
- **Set appropriate expiration times** and use minimal leeway
- **Validate issuer and audience claims** when possible
- **Use strong, random secrets** for HMAC algorithms
- **Keep private keys secure** and rotate them regularly
## Feature Flags
- `hs` - Enable HMAC algorithms (HS256, HS384, HS512)
- `rs` - Enable RSA algorithms (RS256, RS384, RS512)
- `es` - Enable ECDSA algorithms (ES256, ES384, ES512)
- `eddsa` - Enable EdDSA algorithm
- `jwk` - Enable JWK/JWKS support
- `explain` - Enable detailed error explanations
## License
Licensed under the MIT License ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT).