Skip to main content

How to Add Registered Claims to a JWT in Rust with jsonwebtoken

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

The jsonwebtoken crate's encode signs any struct serde can serialize, so the registered claims are fields of your own struct, named exactly iss, sub, aud, iat, nbf, exp and jti. serde turns the struct into the token's payload.

Syntax​

Syntax
#[derive(Serialize, Deserialize)]
struct <Claims> {
iss: String,
sub: String,
aud: String,
iat: u64,
nbf: u64,
exp: u64,
jti: String,
}

let <claims> = <Claims> {
iss: <issuer>,
sub: <subject>,
aud: <audience>,
iat: <now>,
nbf: <now>,
exp: <expiry>,
jti: <unique id>,
};
let <token> = encode(&Header::new(<algorithm>), &<claims>, &<key>)?;
PartWhat it does
#[derive(Serialize, Deserialize)]Lets serde turn the struct into JSON and back.
struct <Claims>Your own struct. Each field becomes a claim with the field's name, so the names must be the registered ones.
String fieldsiss, sub, aud and jti hold text: who issued the token, who it's about, who it's for and its unique ID.
u64 fieldsiat, nbf and exp hold Unix times in seconds.
<now>, <expiry>The current Unix time, and the time the token stops being valid.
encode(...)Writes the header and the claims, signs them with <key> using <algorithm>, and returns the token.

The jsonwebtoken README lists "The claims fields which can be validated" as a struct like this one, with the note that exp is "Required (validate_exp defaults to true in validation)".

The Example​

The example signs a token for a user named ada, issued by https://login.example.org for https://photos.example.org. It sets iat and nbf to now, exp two hours later and jti to a random UUID from the uuid crate. Then it reads the claims back without verifying them, to show what the token holds.

Prerequisites​

  • Rust, with Cargo. This guide uses Rust 1.100.1.

Step 1: Create the Project​

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

cargo new demo creates the project. jsonwebtoken, version 12.0.0 here, needs a cryptography backend chosen by a feature, here rust_crypto. serde's derive feature lets the struct turn into JSON, and the uuid crate's v4 feature makes the random jti.

Step 2: Write the Code​

Replace the contents of src/main.rs:

src/main.rs, with a Claims struct holding iss, sub, aud, iat, nbf, exp and jti, a main that fills it with now, two hours later and a Uuid::new_v4, encodes it with HS256, prints the token, and prints the claims read back with insecure_decode.

src/main.rs
use std::time::{SystemTime, UNIX_EPOCH};

use jsonwebtoken::errors::Error;
use jsonwebtoken::{Algorithm, EncodingKey, Header, dangerous, encode};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

/// The seven registered claims.
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
iss: String,
sub: String,
aud: String,
iat: u64,
nbf: u64,
exp: u64,
jti: String,
}

fn main() -> Result<(), Error> {
// The signing key: 32 random bytes, written as base64.
// It's in the code only for this example; a real app loads it from its configuration.
let key = EncodingKey::from_base64_secret("C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64=")?;

let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("the clock is set before 1970")
.as_secs();
let claims = Claims {
iss: "https://login.example.org".to_owned(),
sub: "ada".to_owned(),
aud: "https://photos.example.org".to_owned(),
iat: now,
nbf: now,
exp: now + 2 * 60 * 60,
jti: Uuid::new_v4().to_string(),
};
let token = encode(&Header::new(Algorithm::HS256), &claims, &key)?;
println!("{token}");

let data = dangerous::insecure_decode::<Claims>(&token)?;
println!("{:?}", data.claims);
Ok(())
}
  • SystemTime::now().duration_since(UNIX_EPOCH) gives the time since 1 January 1970, and as_secs() turns it into whole seconds.
  • now + 2 * 60 * 60 is two hours later.
  • Uuid::new_v4().to_string() makes a random UUID and turns it into the String the field holds.
  • dangerous::insecure_decode reads the claims back without the key. Its documentation warns: "DANGER: This performs zero validation on the JWT". That's fine for looking at a token you just made, never for trusting one.

Step 3: Run It​

Terminal
cargo run -q
Output
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2xvZ2luLmV4YW1wbGUub3JnIiwic3ViIjoiYWRhIiwiYXVkIjoiaHR0cHM6Ly9waG90b3MuZXhhbXBsZS5vcmciLCJpYXQiOjE3OTYwNTk1NTEsIm5iZiI6MTc5NjA1OTU1MSwiZXhwIjoxNzk2MDY2NzUxLCJqdGkiOiIzMTA5MTkzMy1mMWJjLTQ1YTMtOTFjNC1hN2MyOWI3ZWY3MzIifQ.dPIUAPPOtUyXfktPNZqA96xIvvWQ_Feezb3-y2QRej4
Claims { iss: "https://login.example.org", sub: "ada", aud: "https://photos.example.org", iat: 1796059551, nbf: 1796059551, exp: 1796066751, jti: "31091933-f1bc-45a3-91c4-a7c29b7ef732" }

A zsh terminal where cargo run prints the token, then the Claims struct with iss, sub ada, aud, iat and nbf the same number, exp 7200 higher and a jti UUID.

The command is the same in zsh, bash and PowerShell. Your token, times and UUID will differ.

What Happened​

  • The first line is the token, and the second is its claims read back into the struct.
  • The payload holds exactly the struct's fields, in the struct's order: iss, sub, aud, iat, nbf, exp and jti.
  • exp is 7200 higher than iat, the 2 * 60 * 60 seconds.
  • aud is a single string, because the field is a String. A field declared as Vec<String> writes an array instead: two audiences came out as "aud":["https://photos.example.org","https://videos.example.org"].

Because the claims are a struct, a token is only read back when its claims fit the struct's fields and types, as the mistakes below show.

Common Mistakes​

MistakeWhat happensDo this instead
Naming a field issuer instead of issThe token has a claim called issuer and no iss, and a check with set_issuer still accepts it unless iss is in required_spec_claimsUse the registered names
Declaring aud as String when tokens may carry an arrayReading such a token fails with invalid type: sequence, expected a stringDeclare it as Vec<String>
Leaving exp out of the structdecode rejects the token with Missing required claim: expKeep exp. jsonwebtoken requires it by default
Trusting what insecure_decode returnsAnyone can write a token with any claimsVerify with decode and a Validation before using the claims

Troubleshooting​

SymptomLikely causeFix
JSON error: invalid type: sequence, expected a stringThe token's aud is an array and the field is a StringMake the field Vec<String>
Missing required claim: expThe token has no expAdd exp to the struct and set it
"nbf":null in the payloadAn Option field holding NoneAdd #[serde(skip_serializing_if = "Option::is_none")] to the field

FAQ​

How do I make a claim optional?​

Make the field an Option, such as nbf: Option<u64>, and put #[serde(skip_serializing_if = "Option::is_none")] above it. A None is then left out of the token: the payload came out as {"sub":"ada","exp":2000000000}. Without the attribute, it came out as {"sub":"ada","exp":2000000000,"nbf":null}. Reading a token without the claim gives None.

Do I have to set all seven claims?​

No. The JWT standard makes every registered claim optional. jsonwebtoken's decode requires exp by default, though, so a token without it is rejected unless you change required_spec_claims.

Does the order of the fields matter?​

Not to a verifier: claims are looked up by name. serde writes them in the order the struct declares them.

Conclusion​

With jsonwebtoken, the registered claims are fields of your own serde struct, named as the JWT standard names them, and encode turns the struct into the token's payload. Use Vec<String> for an aud that can hold several audiences, and Option with skip_serializing_if for a claim that isn't always there.

Additional Resources​