Skip to main content

How to Verify a JWT in Rust with jsonwebtoken decode

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

The jsonwebtoken crate verifies JSON Web Tokens in Rust with its decode function: give it the token, a decoding key and a Validation that sets the rules, and it returns your claims struct, or an error that says what failed.

Syntax​

Syntax
let data = decode::<ClaimsType>(&token, &DecodingKey::from_base64_secret(secret)?, &Validation::new(Algorithm::HS256))?;
let claims: ClaimsType = data.claims;
PartWhat it does
decode::<ClaimsType>Decodes into your claims struct, which derives serde's Deserialize.
DecodingKey::from_base64_secret(secret)?The key to check the signature with: for HS256, the same secret that signed the token.
Validation::new(Algorithm::HS256)The rules: accept only HS256, and check exp, with a 60-second leeway.
dataA TokenData with the verified claims and the token's header.

The jsonwebtoken documentation for decode: "Decode and validate a JWT. If the token or its signature is invalid or the claims fail validation, it will return an error." On Validation, new will "Create a default validation setup allowing the given alg".

The Example​

The example signs a token for the user ada with the role reader, then decodes it twice: with the key that signed it, and with a different key, the way a token from another app would arrive.

Both keys are 32 random bytes, made with openssl rand -base64 32 and written as base64. They sit in the code only so the example runs as it is. A real application loads its key from configuration and never keeps it in the source.

Prerequisites​

  • Rust, installed with rustup, which comes with Cargo. This guide uses Rust 1.100.0.

Step 1: Create the Project​

Terminal
cargo new demo
cd demo
cargo add jsonwebtoken --features rust_crypto
cargo add serde --features derive

cargo new demo creates the project. The two cargo add commands add jsonwebtoken 12.0.0 with its rust_crypto backend, which it needs to sign and verify, and serde with its derive macros.

Step 2: Write the Code​

Replace the contents of src/main.rs with:

src/main.rs, which defines Claims deriving Debug, Serialize and Deserialize, signs a token for ada with role reader and a 10-minute expiry, decodes it with decode, the right DecodingKey and Validation for HS256, prints the claims, then decodes it with another key and prints Rejected with the error.

src/main.rs
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
use serde::{Deserialize, Serialize};
use std::time::{SystemTime, UNIX_EPOCH};

#[derive(Debug, Serialize, Deserialize)]
struct Claims {
sub: String,
role: String,
exp: u64,
}

fn main() -> Result<(), jsonwebtoken::errors::Error> {
// Two keys, 32 random bytes each, written as base64.
// They're in the code only for this example; a real app loads its key from its configuration.
let secret = "VfosHbT9z3nikPe56UUfKL9Y6mF2oOui09j4GCY0AYs=";
let other_secret = "rAAk7yhJl8rF7vvQeKOeI2ooYrBw9A45aLuMb44gH78=";

let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("the clock is set before 1970")
.as_secs();
let claims = Claims {
sub: "ada".to_owned(),
role: "reader".to_owned(),
exp: now + 600,
};
let token = encode(
&Header::default(),
&claims,
&EncodingKey::from_base64_secret(secret)?,
)?;

let validation = Validation::new(Algorithm::HS256);
let data = decode::<Claims>(
&token,
&DecodingKey::from_base64_secret(secret)?,
&validation,
)?;
println!("{:?}", data.claims);

let other_key = DecodingKey::from_base64_secret(other_secret)?;
if let Err(err) = decode::<Claims>(&token, &other_key, &validation) {
println!("Rejected: {err}");
}
Ok(())
}

decode::<Claims> names the type to decode into. The second decode uses other_key, so it returns an Err, which if let prints.

Step 3: Run It​

Terminal
cargo run -q
Output
Claims { sub: "ada", role: "reader", exp: 1795683191 }
Rejected: InvalidSignature

A zsh terminal where cargo run -q prints the Claims struct with sub ada, role reader and exp, then Rejected: InvalidSignature.

cargo run compiles the program and runs it, and -q hides Cargo's own status lines. With the right key, decode checked the signature and exp and returned the claims. With the other key, the signature didn't match.

The Errors It Returns​

These came from real runs. err.kind() gives an ErrorKind you can match on:

What's wrongPrinted with {}err.kind()
Signed with another key, or the payload was changedInvalidSignatureInvalidSignature
The token expired more than 60 seconds agoExpiredSignatureExpiredSignature
Signed with HS384, but the validation allows HS256InvalidAlgorithmInvalidAlgorithm
The token has no expMissing required claim: expMissingRequiredClaim("exp")
Not a JWT at allInvalidTokenInvalidToken

The Defaults in Validation::new​

Validation::new sets a 60-second leeway and requires exp. The documentation: the leeway will "Add some leeway (in seconds) to the exp and nbf validation to account for clock skew. Defaults to 60", and the required claims default to {"exp"}. Printed from a fresh Validation, leeway was 60 and required_spec_claims was {"exp"}, and a token that had expired 30 seconds earlier still decoded. Set validation.leeway lower if 60 seconds is too generous for you.

Common Mistakes​

MistakeWhat happensDo this instead
Claims without expMissing required claim: expPut exp in your tokens, or change required_spec_claims on purpose
A Validation for another algorithm than the token'sInvalidAlgorithmUse the algorithm the tokens are signed with
No crypto backend feature on the crateThe program panics with Could not automatically determine the process-level CryptoProvider from jsonwebtoken crate features.Add --features rust_crypto (or aws_lc_rs)

Troubleshooting​

SymptomLikely causeFix
InvalidSignatureAnother key signed it, or it was changedCheck with the signing key; reject the token
ExpiredSignatureThe exp passed more than the leeway agoGet a new token
InvalidTokenThe string isn't a JWTCheck what's being passed in

FAQ​

What's inside TokenData?​

The claims, your struct, and the header: for this token, data.header.alg was HS256 and data.header.typ was Some("JWT").

Why does decode need the claims type?​

It deserializes the payload into that struct with serde, so the struct decides which claims you read and their types.

Conclusion​

decode::<Claims>(&token, &DecodingKey::from_base64_secret(secret)?, &Validation::new(Algorithm::HS256)) verifies the signature, the algorithm and exp, and returns your claims. Mind the 60-second default leeway, and match on err.kind() to tell failures apart.

Additional Resources​