JWT Encoder and Decoder in Rust — Code Examples
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.
// 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
}- 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.
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 JavaScript / Node.js
The jsonwebtoken package is the standard Node.js JWT library. Use jwt.sign to create tokens and jwt.verify to validate them.
JWT Encoder and Decoder in Python
PyJWT is the standard Python JWT library. Pass the algorithm explicitly to jwt.decode to prevent algorithm confusion attacks.
JWT Encoder and Decoder in Go
The golang-jwt/jwt package is the maintained fork of the popular dgrijalva/jwt-go library. Define a custom Claims struct for typed access.
JWT Encoder and Decoder in Java
JJWT (io.jsonwebtoken) is the most popular Java JWT library. Use Jwts.builder() to create tokens and Jwts.parser() to verify them.
JWT Encoder and Decoder in PHP
firebase/php-jwt is the standard PHP JWT library. Use JWT::encode to sign and JWT::decode with a Key object to verify.
JWT Encoder and Decoder in Ruby
The jwt gem is the standard Ruby JWT library. Use JWT.encode to sign and JWT.decode with verify=true to validate.
JWT Encoder and Decoder in C# / .NET
C# uses the System.IdentityModel.Tokens.Jwt NuGet package. JwtSecurityTokenHandler handles both signing and validation.