Rust JWT Authentication

Implement JWT authentication in Rust using the jsonwebtoken crate with HMAC-SHA256 signing, claims validation, expiry checking, and Axum extractor for.

RustAuth Jwt

Code

snippet
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:: and serde:: 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

FAQ

What does this need from the package registry?
These are real dependencies: `jsonwebtoken::` and `serde::`. Without them the snippet will not load.