jsonwebtoken crate
Learn what the jsonwebtoken crate provides, how to add it to an Axum project, and how encode and decode turn claims into a signed token and back
A JSON Web Token is a string a server hands to a client after login, and the jsonwebtoken crate is the Rust library that creates and checks those strings. It gives you two functions that do almost all of the work, encode to make a token from a set of claims and decode to check a token and read the claims back out. Around those two functions sit a handful of small types: a header that names the signing algorithm, key types that hold the secret, and a validation type that states which checks decode must run. This page introduces the crate, adds it to a project, and runs a minimal encode and decode round trip.
Where This Fits
The pages before this one built the shape of a token by hand: a claims struct with a user id, a role, and an expiry time, and a login handler that needed a way to turn those claims into something a client could carry. Nothing so far could actually sign anything. The jsonwebtoken crate is the missing tool. It takes the claims struct, signs it with a secret the server keeps, and produces the token string. That string is what protected routes check, what refresh tokens renew, and what role checks read, and all of those uses call the same two functions introduced here.
Think of a wax seal on a letter. The letter is the claims, the wax is the signature, and the signet ring is the secret. Anyone can read the letter, but only the holder of the ring can press a seal that matches. The crate is the workshop that presses the seal and checks it later.
The Smallest Working Version
Start a project with one dependency beyond the usual Axum set. The crate is jsonwebtoken, version 12, and it needs a crypto backend chosen through a feature flag. This book uses rust_crypto, the pure Rust backend, which needs no system libraries.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
jsonwebtoken = { version = "12", features = ["rust_crypto"] }
The serde derive feature matters here, because the claims struct must derive Serialize and Deserialize. Without it, encode cannot turn the struct into JSON and decode cannot turn JSON back into the struct.
The smallest program encodes one token and decodes it again. It uses the claims shape this chapter shares everywhere: sub holds the user id as an i32, role holds "user" or "admin", and exp holds the expiry time as seconds since the Unix epoch, which is the number of seconds since 1 January 1970.
use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation, decode, encode};
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
sub: i32,
role: String,
exp: usize,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let secret = "test-secret-only-for-local-development";
let claims = Claims {
sub: 7,
role: "user".to_string(),
exp: 2_000_000_000,
};
let token = encode(
&Header::default(),
&claims,
&EncodingKey::from_secret(secret.as_bytes())?,
)?;
println!("token: {token}");
let data = decode::<Claims>(
&token,
&DecodingKey::from_secret(secret.as_bytes())?,
&Validation::default(),
)?;
println!("user id: {}", data.claims.sub);
println!("role: {}", data.claims.role);
println!("expiry: {}", data.claims.exp);
Ok(())
}
Run it with cargo run. The output is exactly this, because the same claims and the same secret always produce the same token:
token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjcsInJvbGUiOiJ1c2VyIiwiZXhwIjoyMDAwMDAwMDAwfQ.-u_qNR8ZkIdu_CRBV7OYc2MlwCPa-JenOD0jNj67m48
user id: 7
role: user
expiry: 2000000000
The token has three parts separated by dots. The first part names the token type and the algorithm, the second part holds the claims as JSON, and the third part is the signature. The first two parts are only base64url encoded, which is a way of writing bytes as text that is safe to put in a URL, so anyone who holds the token can read them. The signature is what makes the token trustworthy, and only the secret can produce a matching one.
Working Setup:
If cargo run prints a three-part token and then the same user id, role, and expiry you put into the claims, the crate is installed, the backend feature is on, and the round trip works. Everything later in this chapter builds on these two calls.
Test Secret Only:
The string "test-secret-only-for-local-development" is a throwaway secret for examples on this page. It must never be used anywhere real. A real secret comes from the JWT_SECRET environment variable, is long and random, and is never written into source code. A secret that appears in a repository is a secret every reader of that repository knows.
The Pieces the Crate Provides
The crate's public surface is small, and each piece has one job. The six names below are the ones this chapter uses.
encode and decode
encode takes three arguments: a header, the claims, and an encoding key. It returns the token as a String, wrapped in a Result because signing can fail. decode takes three arguments too: the token string, a decoding key, and a Validation. It returns a TokenData struct, which has two fields, header and claims, where claims is your own struct. The type parameter on decode::<Claims> tells the compiler which struct the claims JSON should be parsed into.
Header and Algorithm
Header describes the token's first part. Header::default() sets the type to JWT and the algorithm to HS256, which is a signing method that uses one shared secret for both signing and checking. Algorithm is an enum of the signing methods the crate supports: HS256, HS384, and HS512 use a shared secret, while RS256, ES256, and EdDSA use a pair of keys instead. This chapter uses HS256 throughout, because one secret is the simplest setup that is still correct for a single server.
To pick a different algorithm, build the header with Header::new and pass a matching Validation to decode:
use jsonwebtoken::{Algorithm, Header, Validation};
let mut header = Header::new(Algorithm::HS512);
header.kid = Some("key-1".to_string());
let validation = Validation::new(Algorithm::HS512);
The kid field is a key id, a short label that names which key signed the token. It is useful when a server rotates between several secrets and needs to know which one to check with. Setting it is optional, and a token without it decodes exactly the same way.
EncodingKey and DecodingKey
EncodingKey holds the secret used to sign, and DecodingKey holds the secret used to check. For HS256 both come from the same secret bytes, through from_secret. In version 12 of the crate these two constructors return a Result, so the call ends with ?, as in the example above. The only way they fail for a plain secret is an empty one, which the crate rejects with an InvalidKeyFormat error. An empty secret would sign every token with nothing, so the crate refuses to build a key from it.
use jsonwebtoken::{DecodingKey, EncodingKey};
let encoding_key = EncodingKey::from_secret(secret.as_bytes())?;
let decoding_key = DecodingKey::from_secret(secret.as_bytes())?;
Two other constructors exist for secrets stored in base64 form, from_base64_secret and from_urlsafe_base64_secret, and key-pair constructors such as from_rsa_pem exist for the RS256 family. This chapter does not use them, because a plain shared secret covers the whole chapter.
Version 12 Changed from_secret:
Older versions of the crate returned the key directly from from_secret, with no Result. Version 12 returns a Result, so code written against an older version fails to compile with a type error about finding a Result where a key was expected. The fix is a ? after the call. If you copy a from_secret example from a blog post and it does not compile, this change is the first thing to check.
Validation
Validation states the rules decode must enforce. Validation::default() allows only HS256 and requires the exp claim to be present, and it checks that the token has not expired. That default is the right choice for this chapter: it refuses tokens signed with a different algorithm, and it refuses tokens that carry no expiry at all.
A token that fails any of these checks is rejected by decode with an error, and the handler answers 401. The error's kind names the reason: ExpiredSignature for an expired token, InvalidSignature for a signature made with a different secret, and InvalidToken for a string that is not a token at all. The crate also exposes Validation::new for a different algorithm, and a leeway field, measured in seconds, that tolerates small clock differences between the machine that signed the token and the machine that checks it. A leeway of 60 seconds is common when two servers do not share exactly the same clock.
use jsonwebtoken::{Algorithm, Validation};
let mut validation = Validation::new(Algorithm::HS512);
validation.leeway = 60;
What a Token Is Made Of
A token is three base64url parts joined by dots: header, payload, signature. The header says which algorithm signed it. The payload is the claims as JSON. The signature is computed over the first two parts with the secret, using the HMAC-SHA256 construction for HS256. HMAC is a standard way of combining a secret with a message to produce a short fingerprint, and SHA-256 is the hash function inside it.
The important property follows directly from that construction. Changing even one character of the header or the payload changes the signature the secret would produce, so a token whose payload was edited after signing fails the check. The server never needs to remember the tokens it issued, because the signature carries the proof. It only needs the secret, and any server holding the same secret accepts the same tokens.
That property has a limit a beginner must understand early. The payload is encoded, not encrypted. Anyone who receives the token can decode the first two parts and read the claims, including the user id and the role. A token must never carry a password, an email address, or anything else the holder should not see. It carries an id and a role, and the server looks up anything sensitive from its own database.
Stateless Does Not Mean Unchecked:
A token is sometimes described as stateless, because the server does not store it. Stateless does not mean the server trusts whatever arrives. Every request still runs decode, which checks the signature and the expiry before the handler sees the claims. A token the server did not sign is refused, and a token past its expiry is refused, no matter how correctly shaped it looks.
Why One Crate Does Both Jobs
Signing and checking could be two different libraries, but they share the secret, the algorithm, and the claims type, so keeping them in one crate keeps those three things consistent. A token signed with HS256 and checked with HS256 is the same token on both sides. If the two sides used different libraries with different defaults, a token could be signed one way and checked another, and the mismatch would surface as a confusing runtime failure instead of a compile-time one.
The crate also keeps validation separate from decoding. decode needs a Validation argument, so the caller states the rules in the open instead of relying on hidden defaults. A reader of the handler can see which algorithms are allowed and whether an expiry is required, without opening the crate source.
A Richer Example With Helpers
Real handlers do not call encode and decode directly with raw literals. They call small helpers that hide the secret handling and the expiry arithmetic. The helpers below are the ones this chapter reuses: issue_access_token builds a token that lives for 15 minutes, and decode_access_token checks one and returns the claims.
use std::time::{SystemTime, UNIX_EPOCH};
use jsonwebtoken::{DecodingKey, EncodingKey, Header, TokenData, Validation, decode, encode};
use serde::{Deserialize, Serialize};
use crate::errors::AppError;
pub const ACCESS_TOKEN_SECONDS: u64 = 900;
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
pub sub: i32,
pub role: String,
pub exp: usize,
}
pub fn jwt_secret() -> String {
std::env::var("JWT_SECRET")
.unwrap_or_else(|_| "test-secret-only-for-local-development".to_string())
}
fn now_seconds() -> usize {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system time before epoch")
.as_secs() as usize
}
pub fn issue_access_token(user_id: i32, role: &str, secret: &str) -> Result<String, AppError> {
let claims = Claims {
sub: user_id,
role: role.to_string(),
exp: now_seconds() + ACCESS_TOKEN_SECONDS as usize,
};
let token = encode(
&Header::default(),
&claims,
&EncodingKey::from_secret(secret.as_bytes())?,
)?;
Ok(token)
}
pub fn decode_access_token(token: &str, secret: &str) -> Result<TokenData<Claims>, AppError> {
let data = decode::<Claims>(
token,
&DecodingKey::from_secret(secret.as_bytes())?,
&Validation::default(),
)?;
Ok(data)
}
The expiry is computed from the current time, not from a fixed date, so every token lives for 15 minutes from the moment it is issued. SystemTime::now() gives the current time, duration_since(UNIX_EPOCH) turns it into seconds since 1970, and adding 900 gives the expiry. exp is a usize, a plain unsigned integer, because the JWT standard defines it as seconds since the epoch, not as a formatted date string.
The error type is the chapter's shared AppError, and the From<jsonwebtoken::errors::Error> conversion in the errors module turns any crate error into Unauthorized, so a handler that calls these helpers can use ? and let a bad token become a 401 automatically. The conversion looks like this:
impl From<jsonwebtoken::errors::Error> for AppError {
fn from(error: jsonwebtoken::errors::Error) -> Self {
eprintln!("token error: {error}");
AppError::Unauthorized
}
}
Logging the error on the server and sending only {"error": "unauthorized"} to the client is deliberate. The log keeps the detail for debugging, and the client gets nothing an attacker could use to learn why a forged token failed.
Use the helpers from a small demo binary to see the failure cases. An expired token is built by passing an expiry in the past, and a wrong-secret token is checked with a different secret:
use axum_project::auth::{decode_access_token, issue_access_token};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let secret = "test-secret-only-for-local-development";
let token = issue_access_token(7, "user", secret)?;
println!("fresh token decodes: {}", decode_access_token(&token, secret).is_ok());
println!(
"wrong secret decodes: {}",
decode_access_token(&token, "someone-elses-secret").is_ok()
);
let tampered = format!("{}.AAAA.{}", token.split('.').next().unwrap(), token.rsplit('.').next().unwrap());
println!("tampered token decodes: {}", decode_access_token(&tampered, secret).is_ok());
Ok(())
}
The output, verified by running this code, is three lines that state the security rule of the whole chapter:
fresh token decodes: true
wrong secret decodes: false
tampered token decodes: false
How Encoding and Decoding Flow
The two functions are mirror images, and the flow in each direction is short enough to hold in one picture:
Claims struct (sub, role, exp)
|
v
encode with Header::default() and EncodingKey
|
v
header.payload.signature (a String the client stores)
|
v
decode with DecodingKey and Validation::default()
|
v
signature checked, then exp checked
|
v
TokenData { header, claims } (or an error)
encode never talks to a database, reads no file, and makes no network call. It is a pure function of the claims, the header, and the secret, which is why two tokens built from identical claims inside the same second are byte-identical: there is no randomness inside a token. decode is equally self-contained. It needs only the token, the secret, and the validation rules.
Testing the Round Trip
Unit tests belong next to the helpers, because the round trip is the contract the rest of the chapter depends on. These tests ran against jsonwebtoken 12.0.0 and all pass:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trip_keeps_claims() {
let secret = "test-secret-only-for-local-development";
let token = issue_access_token(7, "user", secret).unwrap();
assert_eq!(token.split('.').count(), 3);
let data = decode_access_token(&token, secret).unwrap();
assert_eq!(data.claims.sub, 7);
assert_eq!(data.claims.role, "user");
}
#[test]
fn wrong_secret_is_rejected() {
let secret = "test-secret-only-for-local-development";
let token = issue_access_token(7, "user", secret).unwrap();
assert!(decode_access_token(&token, "someone-elses-secret").is_err());
}
#[test]
fn expired_token_is_rejected() {
let secret = "test-secret-only-for-local-development";
let claims = Claims { sub: 7, role: "user".to_string(), exp: 1 };
let token = encode(
&Header::default(),
&claims,
&EncodingKey::from_secret(secret.as_bytes()).unwrap(),
)
.unwrap();
assert!(decode_access_token(&token, secret).is_err());
let raw_error = decode::<Claims>(
&token,
&DecodingKey::from_secret(secret.as_bytes()).unwrap(),
&Validation::default(),
)
.unwrap_err();
assert_eq!(
raw_error.kind(),
&jsonwebtoken::errors::ErrorKind::ExpiredSignature
);
}
}
The expired test builds its token by hand with exp: 1, which is one second after the epoch, so it is expired by decades. That is simpler than waiting 15 minutes, and it exercises exactly the check that matters. The test first checks the helper rejects the token, then calls the crate's decode directly and checks the error kind is ExpiredSignature, because the chapter's AppError conversion turns every token error into the same generic Unauthorized before the handler sees it. In a handler the client would still see only the generic 401 body.
Run the tests with cargo test. The jsonwebtoken dependency needs no database and no server, so these tests run anywhere.
Common Beginner Mistakes
Forgetting the crypto backend feature
// Wrong - fails to compile
jsonwebtoken = "12"
Without a backend feature, the crate has no signing code at all, and compilation fails with an error saying a crypto provider is required. The dependency must name one backend, rust_crypto or aws_lc_rs, and at most one may be enabled. Enabling both is also an error. Pick rust_crypto and move on.
Two Backends Is an Error:
jsonwebtoken = { version = "12", features = ["rust_crypto", "aws_lc_rs"] } does not give you a spare backend. The crate refuses to compile when both are enabled, because it would not know which one to use. One backend, chosen once, for the whole project.
Calling from_secret without handling the Result
// Wrong - fails to compile against version 12
let key = EncodingKey::from_secret(secret.as_bytes());
let token = encode(&Header::default(), &claims, &key)?;
Version 12 returns a Result from from_secret, so key here is a Result, not a key, and encode rejects it. The fix is a ? on the from_secret call, which is what every example on this page does. The error message names the mismatch plainly: expected &EncodingKey, found &Result<EncodingKey, Error>.
Reading a token without checking it
// Wrong - the header is not proof of anything
let header = jsonwebtoken::decode_header(&token)?;
println!("algorithm: {}", header.alg);
decode_header reads only the first part of the token. It performs no signature check and no expiry check, so it accepts a token anyone typed by hand. It exists for the narrow case where the server must read the kid before it knows which key to check with. It must never be the check that decides whether a request is allowed. The only function that answers that question is decode.
Building a token with no expiry
// Wrong - Validation::default() rejects this token
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
sub: i32,
role: String,
}
A claims struct without exp cannot be decoded with Validation::default(), because the default requires the claim to be present. The decode fails with a missing-claim error, and the login that issued the token appears to work while every protected route answers 401. Every claims struct in this chapter carries exp, and every token is issued with a real expiry time.
Hardcoding the secret in source code
// Wrong - the secret is now in every checkout of the repository
let secret = "my-production-secret-123";
A secret in source code is a secret shared with everyone who can read the repository, including future readers after a leak. Read it from the JWT_SECRET environment variable, keep a throwaway literal only in local examples, and rotate the secret at once if a real one ever appears in a commit.
Final Complete Example
The finished module below is the one the rest of the chapter imports. It holds the claims struct, the two helpers, and the secret reader, with nothing else:
use std::time::{SystemTime, UNIX_EPOCH};
use jsonwebtoken::{DecodingKey, EncodingKey, Header, TokenData, Validation, decode, encode};
use serde::{Deserialize, Serialize};
use crate::errors::AppError;
pub const ACCESS_TOKEN_SECONDS: u64 = 900;
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
pub sub: i32,
pub role: String,
pub exp: usize,
}
#[derive(Debug, Clone)]
pub struct AuthUser {
pub user_id: i32,
pub role: String,
}
pub fn jwt_secret() -> String {
std::env::var("JWT_SECRET")
.unwrap_or_else(|_| "test-secret-only-for-local-development".to_string())
}
fn now_seconds() -> usize {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system time before epoch")
.as_secs() as usize
}
pub fn issue_access_token(user_id: i32, role: &str, secret: &str) -> Result<String, AppError> {
let claims = Claims {
sub: user_id,
role: role.to_string(),
exp: now_seconds() + ACCESS_TOKEN_SECONDS as usize,
};
let token = encode(
&Header::default(),
&claims,
&EncodingKey::from_secret(secret.as_bytes())?,
)?;
Ok(token)
}
pub fn decode_access_token(token: &str, secret: &str) -> Result<TokenData<Claims>, AppError> {
let data = decode::<Claims>(
token,
&DecodingKey::from_secret(secret.as_bytes())?,
&Validation::default(),
)?;
Ok(data)
}
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
jsonwebtoken = { version = "12", features = ["rust_crypto"] }
thiserror = "2"
Run cargo test and then cargo run on the demo binary. The tests confirm the round trip, and the demo confirms the three-way split: a fresh token decodes, a token checked with the wrong secret does not, and a tampered token does not.
Summary
The crate is small on purpose: two functions, two key types, a header, and a validation type, and that is the whole surface a chapter of authentication needs. The decision that matters most is not which algorithm to pick, it is the rule that no token is trusted until decode has checked its signature and its expiry, with a Validation that names the allowed algorithm and requires an expiry. Once that rule is in place, the rest of the chapter is a matter of where tokens are issued, where they are checked, and how long each kind of token is allowed to live. The next question to carry forward is not how to make a token, but how to make one that stops working when it should: a short-lived access token paired with a revocable refresh token, which is a storage problem as much as a signing problem.