JsonWebToken Claims Expiry Validation
Verify JWT claims and expiry with jsonwebtoken crate in Rust authentication flows.
Code
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::andserde::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
JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.