DevToolsForYou

JWT Encoder and Decoder in Rust — Code Examples

JWT Encoder and Decoder in RustUse the online tool →

JSON Web Tokens (JWTs) are a compact, URL-safe format for transmitting claims between parties. A JWT has three Base64url-encoded parts separated by dots: header, payload, and signature. Here is how to sign, verify, and decode JWTs in each language.

The jsonwebtoken crate handles JWT signing and verification. Define a Claims struct with serde and use EncodingKey / DecodingKey.

Rust
// Cargo.toml:
// jsonwebtoken = "9"
// serde = { version = "1", features = ["derive"] }
use jsonwebtoken::{encode, decode, Header, Algorithm, Validation, EncodingKey, DecodingKey};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct Claims {
    user_id: u32,
    name: String,
    role: String,
    exp: u64, // Unix timestamp
}

fn main() {
    let secret = b"my-secret-key";
    let claims = Claims {
        user_id: 42,
        name: "Alice".to_string(),
        role: "admin".to_string(),
        exp: 9999999999,
    };

    // Sign (encode)
    let token = encode(
        &Header::default(), // HS256
        &claims,
        &EncodingKey::from_secret(secret),
    ).unwrap();
    println!("{}", token);

    // Verify and decode
    let data = decode::<Claims>(
        &token,
        &DecodingKey::from_secret(secret),
        &Validation::new(Algorithm::HS256),
    ).unwrap();
    println!("{}", data.claims.name);    // Alice
    println!("{}", data.claims.user_id); // 42
}
Notes & gotchas
  • exp must be a u64 Unix timestamp; the crate validates it automatically during decode.
  • For RS256, use EncodingKey::from_rsa_pem and DecodingKey::from_rsa_pem with PEM bytes.
  • Validation::new(Algorithm::HS256) enforces the algorithm — never use Validation::default() in production as it may be permissive.
Try it in your browser

Need to jwt encode/decode without writing code? The JWT Encoder and Decoder runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open JWT Encode/Decode
JWT Encoder and Decoder in other languages