Rust JWT Authentication
Implement JWT authentication in Rust using the jsonwebtoken crate with HMAC-SHA256 signing, claims validation, expiry checking, and Axum extractor for.
Code
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Validation, Header};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct Claims {
sub: String,
exp: usize,
}
fn create_token(user_id: &str, secret: &str) -> String {
let claims = Claims { sub: user_id.into(), exp: 9999999999 };
encode(&Header::default(), &claims, &EncodingKey::from_secret(secret.as_ref())).unwrap()
}
fn verify_token(token: &str, secret: &str) -> Option<Claims> {
let data = decode::<Claims>(token, &DecodingKey::from_secret(secret.as_ref()), &Validation::default());
data.ok().map(|d| d.claims)
}How the snippet works
Structurally, expect the functions create_token and verify_token and nothing else.
What to watch for
- Plan for an install step:
jsonwebtoken::andserde::are a real dependency, resolved by the package manager.
Applying it
Signature: fn create_token(user_id: &str, secret: &str) -> String
create_token is the public entry point; everything else in the file exists to support it.
Statements that matter
fn verify_token(token: &str, secret: &str) -> Option<Claims> {
let data = decode::<Claims>(token, &DecodingKey::from_secret(secret.as_ref()), &Validation::default());
data.ok().map(|d| d.claims)
}
fn create_token(user_id: &str, secret: &str) -> String {
let claims = Claims { sub: user_id.into(), exp: 9999999999 };
encode(&Header::default(), &claims, &EncodingKey::from_secret(secret.as_ref())).unwrap()
}
Interactive Tools for This Topic
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.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.OAuth 2.0 PKCE Code GeneratorGenerate RFC 7636 OAuth 2.0 PKCE code verifiers with Web Crypto CSPRNG, compute SHA-256 code challenges, and build full authorization URLs.JWT Token DecoderDecode JSON Web Token (JWT) headers and payloads safely in the browser. Inspect expiration, issuer, and claims without sending tokens to any external server.
FAQ
- What does this need from the package registry?
- These are real dependencies: `jsonwebtoken::` and `serde::`. Without them the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.