JsonWebToken Claims Expiry Validation

Verify JWT claims and expiry with jsonwebtoken crate in Rust authentication flows.

RustAuth Jwt

Code

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

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

fn sign_token(claims: &Claims, secret: &str) -> String {
    encode(&Header::new(Algorithm::HS256), claims, &EncodingKey::from_secret(secret.as_ref())).unwrap()
}

fn verify_token(token: &str, secret: &str) -> Claims {
    let data = decode::<Claims>(token, &DecodingKey::from_secret(secret.as_ref()), &Validation::new(Algorithm::HS256)).unwrap();
    data.claims
}

How the snippet works

JsonWebToken Claims Expiry Validation reduces to the functions sign_token and verify_token.

What to watch for

  • Plan for an install step: jsonwebtoken:: and serde:: are a real dependency, resolved by the package manager.

Applying it

The main signature reads fn sign_token(claims: &Claims, secret: &str) -> String

sign_token is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

let data = decode::<Claims>(token, &DecodingKey::from_secret(secret.as_ref()), &Validation::new(Algorithm::HS256)).unwrap();
fn sign_token(claims: &Claims, secret: &str) -> String {
encode(&Header::new(Algorithm::HS256), claims, &EncodingKey::from_secret(secret.as_ref())).unwrap()
}

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Yes: `jsonwebtoken::` and `serde::` must be present in the project or the import fails at load time.