How to Use JWT Tokens in Rust (jsonwebtoken crate)

Use the `jsonwebtoken` crate to encode claims into a token and decode them back in your Axum handlers.

How to Use JWT Tokens in Rust (jsonwebtoken crate)

Use the jsonwebtoken crate to encode claims into a token and decode them back in your Axum handlers.

use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct Claims {
    sub: String,
    exp: usize,
}

fn main() {
    let secret = "my_secret_key";
    let encoding_key = EncodingKey::from_secret(secret.as_bytes());
    let decoding_key = DecodingKey::from_secret(secret.as_bytes());

    let claims = Claims { sub: "user@example.com".to_string(), exp: 2000000000 };
    let token = encode(&Header::default(), &claims, &encoding_key).unwrap();

    let token_data = decode::<Claims>(&token, &decoding_key, &Validation::default()).unwrap();
    println!("Decoded user: {}", token_data.claims.sub);
}