Skip to main content

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

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

With the jsonwebtoken crate, custom claims are more fields in your own serde struct, next to registered claims such as sub and exp. A String, a Vec and a nested struct become a JSON string, array and object, and #[serde(rename = "...")] gives a claim a name that can't be a Rust field name, such as a URL.

Syntax​

Syntax
#[derive(Serialize, Deserialize)]
struct Claims {
<registered claim>: <type>,
<custom claim>: <type>,
#[serde(rename = "<claim name>")]
<field>: <type>,
}

let <token> = encode(&Header::new(<algorithm>), &<claims>, &<encoding key>)?;
let <data> = decode::<Claims>(&<token>, &<decoding key>, &<validation>)?;
PartWhat it does
struct ClaimsYour own struct, with any name. Each field becomes a claim with the field's name.
<registered claim>A claim the JWT standard defines, such as sub or exp, named exactly as the standard names it.
<custom claim>A claim of your own, such as name or roles.
<type>String, a number type, bool, a Vec such as Vec<String>, an Option, or a struct of your own, which becomes a JSON object.
#[serde(rename = "<claim name>")]Gives the claim a name that can't be a Rust field name, such as a URL.
encode(...)Signs the claims with the key and returns the token.
decode::<Claims>(...)Verifies the token with the key and the Validation, and reads its claims into the struct.

RFC 7519, the JWT standard, says that "Claim Names can be defined at will by those using JWTs", and that to prevent collisions a new name should be registered with IANA or be "a value that contains a Collision-Resistant Name", such as a URL on a domain you control. The jsonwebtoken README lists the registered claims as "The claims fields which can be validated"; the custom ones are yours to check.

The Example​

The example signs a token for Ada at a photo site. Besides four registered claims, it carries three custom claims of three kinds: name, a string; roles, a list; and https://photos.example.org/quota, an object, named with a URL on the site's own domain. The code prints the token, verifies it, prints the claims it got back, then reads one value of each kind.

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 new demo creates the project. jsonwebtoken, version 12.0.0 here, needs a cryptography backend chosen by a feature, here rust_crypto, and serde's derive feature lets the claims struct turn into JSON and back.

Step 2: Write the Code​

Replace the contents of src/main.rs:

src/main.rs, with a Quota struct holding albums and storage_gb, a Claims struct holding iss, sub, aud, exp, name, roles and a quota field renamed to https://photos.example.org/quota, and a main that encodes the claims with HS256, prints the token, decodes it with a Validation that sets the issuer and the audience, and prints the claims and one value of each kind.

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

use jsonwebtoken::errors::Error;
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
use serde::{Deserialize, Serialize};

/// A custom claim whose value is an object.
#[derive(Debug, Serialize, Deserialize)]
struct Quota {
albums: u32,
storage_gb: u32,
}

/// Four registered claims, then three custom ones.
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
iss: String,
sub: String,
aud: String,
exp: u64,
name: String,
roles: Vec<String>,
#[serde(rename = "https://photos.example.org/quota")]
quota: Quota,
}

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 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(),
exp: now + 60 * 60,
name: "Ada".to_owned(),
roles: vec!["editor".to_owned(), "viewer".to_owned()],
quota: Quota {
albums: 10,
storage_gb: 50,
},
};
let token = encode(
&Header::new(Algorithm::HS256),
&claims,
&EncodingKey::from_base64_secret(secret)?,
)?;
println!("{token}");

let mut validation = Validation::new(Algorithm::HS256);
validation.set_issuer(&["https://login.example.org"]);
validation.set_audience(&["https://photos.example.org"]);
let data = decode::<Claims>(&token, &DecodingKey::from_base64_secret(secret)?, &validation)?;
println!("{:?}", data.claims);

let read = data.claims;
println!("{} | {} | {}", read.name, read.roles.join(", "), read.quota.albums);
Ok(())
}
  • struct Quota is the value of one custom claim. serde writes a struct as a JSON object.
  • roles: Vec<String> is a list, which serde writes as a JSON array.
  • #[serde(rename = "https://photos.example.org/quota")] names the quota field with a URL on the photo site's own domain.
  • Validation::new(Algorithm::HS256), with set_issuer and set_audience, makes decode accept only HS256 tokens from that issuer for that audience. It checks exp too, by default.
  • decode::<Claims> verifies the token and reads its claims into a Claims, which data.claims holds.
  • read.roles.join(", ") joins the roles into one string, and read.quota.albums reads a number from inside the object.

Step 3: Run It​

Terminal
cargo run -q
Output
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2xvZ2luLmV4YW1wbGUub3JnIiwic3ViIjoiYWRhIiwiYXVkIjoiaHR0cHM6Ly9waG90b3MuZXhhbXBsZS5vcmciLCJleHAiOjE3OTYzMDE4NzAsIm5hbWUiOiJBZGEiLCJyb2xlcyI6WyJlZGl0b3IiLCJ2aWV3ZXIiXSwiaHR0cHM6Ly9waG90b3MuZXhhbXBsZS5vcmcvcXVvdGEiOnsiYWxidW1zIjoxMCwic3RvcmFnZV9nYiI6NTB9fQ.j118p0a9b4m5pn1FRu6AkguGcuEs2px63FbXWZmnep0
Claims { iss: "https://login.example.org", sub: "ada", aud: "https://photos.example.org", exp: 1796301870, name: "Ada", roles: ["editor", "viewer"], quota: Quota { albums: 10, storage_gb: 50 } }
Ada | editor, viewer | 10

A zsh terminal where cargo run -q prints the token, then the Claims struct with iss, sub ada, aud, exp, name Ada, roles editor and viewer, and the quota with albums 10 and storage_gb 50, then Ada, editor, viewer and 10 separated by bars.

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

What Happened​

  • The claims came back into the struct: name: "Ada", roles: ["editor", "viewer"], and the quota as Quota { albums: 10, storage_gb: 50 }.
  • decode accepted the token: the signature matched, exp wasn't past, and iss and aud were the ones the Validation expects.
  • The last line read one value of each kind: the string, the list joined with a comma, and a number from inside the object.

Inside the token, the payload (its middle piece) holds the JSON "roles":["editor","viewer"] and "https://photos.example.org/quota":{"albums":10,"storage_gb":50}: the field quota went out under its URL name.

Common Mistakes​

MistakeWhat happensDo this instead
A field for a custom claim the token doesn't carrydecode fails with JSON error: missing field `name` at line 1 column 30Make the field an Option, such as nickname: Option<String>: for a token without the claim, it came back as None
A field whose type doesn't match the claim, such as roles: Vec<String> for a token with "roles":"editor"decode fails with JSON error: invalid type: string "editor", expected a sequence at line 1 column 46Give the field the type of the claim's JSON value
Trusting a custom claim because decode succeededdecode checks the registered claims you set in the Validation, not what the custom ones sayCheck the values your code depends on, such as the roles, yourself

Troubleshooting​

SymptomLikely causeFix
JSON error: missing field `...` from decodeThe token lacks a claim that the struct requiresUse Option for claims that may be missing
JSON error: invalid type: ... from decodeThe claim's JSON type differs from the field's typeChange the field's type to match the claim

FAQ​

Does the struct have to list every claim in the token?​

No. decode skipped the claims the struct didn't list: a token with an extra theme claim decoded into a struct without it. To see every claim, decode into serde_json::Value, with serde_json added to the project: it printed {"exp":1796301790,"name":"Ada","sub":"ada","theme":"dark"}.

Should every custom claim be named with a URL?​

No. A URL on your own domain is for claims that other services might name the same way. RFC 7519 also allows Private Names that only the token's producer and consumer agree on, such as name and roles here, but it warns that "Private Claim Names are subject to collision and should be used with caution."

Can a custom claim be a number or a bool?​

Yes. In my check, a struct with beta: bool and albums: u32 as claims set to true and 10 gave a token holding "beta":true and "albums":10, and decode gave back true and 10.

Conclusion​

In jsonwebtoken, custom claims are fields of your own serde struct: String, Vec and nested structs become JSON strings, arrays and objects. Name a claim with a URL on your own domain through #[serde(rename)] when it might collide, use Option for claims that may be missing, and decode with a Validation before you use any of them.

Additional Resources​