Expand description
A flexible utility library for encoding and decoding JSON Web Tokens (JWT).
This crate provides a type state API for creating, signing, and verifying JWTs with support for HMAC-SHA256 (HS256) and RSA-SHA256 (RS256).
§Examples
§Using HS256 (HMAC-SHA256)
use jwtoken::{random_secret, HS256, Jwt, Encoder, Decoded};
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct MyClaims {
sub: String,
name: String,
iat: u64,
}
fn main() -> Result<(), jwtoken::JwtError> {
let secret = random_secret();
let algorithm = HS256::new(&secret);
let claims = MyClaims {
sub: "1234567890".to_string(),
name: "John Doe".to_string(),
iat: 1516239022,
};
// Encoding a JWT
let token = Jwt::<Encoder, MyClaims>::new(claims)
.encode(&algorithm)?;
println!("Generated token: {}", token);
// Decoding and verifying the same JWT
let decoded = Jwt::<Decoded, MyClaims>::decode(&token, &algorithm)?;
println!("Decoded claims: {:?}", decoded.claims());
Ok(())
}
§Using RS256 (RSA-SHA256)
use jwtoken::{rsa_keypair, RS256Signer, RS256Verifier, Jwt, Encoder, Decoded};
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct MyClaims {
sub: String,
name: String,
admin: bool,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Generate a new RSA key pair
let (private_key, public_key) = rsa_keypair()?;
// Create a signer with the private key and a verifier with the public key
let signer = RS256Signer::new(private_key);
let verifier = RS256Verifier::new(public_key);
let claims = MyClaims {
sub: "user-id-42".to_string(),
name: "Jane Doe".to_string(),
admin: true,
};
// Encoding a JWT
let token = Jwt::<Encoder, MyClaims>::new(claims)
.encode(&signer)?;
println!("Generated RS256 token: {}", token);
// Decoding and verifying the same JWT
let decoded = Jwt::<Decoded, MyClaims>::decode(&token, &verifier)?;
println!("Decoded RS256 claims: {:?}", decoded.claims());
// You can also verify with the signer itself, as it holds the public key
let decoded_with_signer = Jwt::<Decoded, MyClaims>::decode(&token, &signer)?;
assert_eq!(decoded.claims(), decoded_with_signer.claims());
Ok(())
}
Structs§
- Decoded
- A decoded state JWT to be inspected
- Encoder
- A encoder state for creating JWTs.
- Jwt
- A JSON Web Token (JWT) in a specific state (either
Encoder
orDecoded
).
Enums§
- JwtError
- Represents errors that can occur during JWT operations.
Traits§
Type Aliases§
- Headers
- JWT headers map. Values “typ” to “JWT” and “alg” to the appropriate algorithm are internally set.