Custom Claims
The registered claims say who made a token, who it's about, who it's for and when it counts. They don't say what the user may do. That's the job of custom claims: names and values you choose, such as a user's roles or the plan they pay for. This tutorial explains how to name a custom claim so it can't collide with anyone else's, what a claim can hold, and why an API checks every claim before it uses one. Then it builds a sign-in service that adds three custom claims and an orders API that decides each order from them, in eight languages. Every token in the run carries a valid signature, and the orders API still turns down three of the four orders.
What a Custom Claim Is
A JWT's payload is a JSON object, and each of its members is a claim: a name and a value. Registered Claims covered the seven names that RFC 7519, the JWT standard, defines itself. Every other claim is up to you. Section 4.2 of the standard puts it plainly: "Claim Names can be defined at will by those using JWTs." This course calls those claims custom claims.
A claim's value isn't limited to text either. Section 2 of RFC 7519 says "A Claim Value can be any JSON value": a string, a number, true or false, null, an array or an object.
Decoded, the payload of a token with custom claims looks like this. It's the token the Python program in this tutorial printed for its user, Zara:
{
"iss": "https://auth.example.com",
"sub": "user-42",
"aud": "https://orders.example.com",
"iat": 1796284363,
"exp": 1796285263,
"name": "Zara",
"roles": [
"customer",
"beta-tester"
],
"https://orders.example.com/plan": {
"name": "pro",
"order_limit": 500
}
}
The first five claims are registered ones. The last three are custom:
name, a string: the user's name, to show on screen.roles, an array of strings: what the user is to the application. Zara is acustomerand abeta-tester.https://orders.example.com/plan, an object: the plan Zara pays for,pro, and the most she may order at once,500.
Three Kinds of Claim Names
RFC 7519 sorts claim names into three kinds: "There are three classes of JWT Claim Names: Registered Claim Names, Public Claim Names, and Private Claim Names."
| Kind | What it is | Examples |
|---|---|---|
| Registered | The seven names RFC 7519 defines in section 4.1 | iss, sub, aud, exp, nbf, iat, jti |
| Public | A new name registered in IANA's JSON Web Token Claims registry, or a name that contains a collision-resistant name | name and roles from the registry; https://orders.example.com/plan |
| Private | Any other name, agreed between the service that makes the token and the one that reads it | plan, tenant, permissions |
The public kind is how the standard keeps names apart. Section 4.2 says that "in order to prevent collisions, any new Claim Name should either be registered in the IANA "JSON Web Token Claims" registry established by Section 10.1 or be a Public Name: a value that contains a Collision-Resistant Name." A collision-resistant name lives in a namespace where names are "highly unlikely to collide with other names", and the standard gives domain names, object identifiers (OIDs) and UUIDs as examples.
A private name is anything else, such as a short plan. The standard allows it, with a warning in section 4.3: "Unlike Public Claim Names, Private Claim Names are subject to collision and should be used with caution."
Name a Custom Claim So It Can't Collide
Two parties collide when they use the same claim name for different things. Say the sign-in service also makes tokens for a billing API that uses plan for how often a customer pays, such as "monthly". Then one token can't carry both, and an API that reads plan gets a value that means something else to it.
Three rules keep that from happening:
- Look in the registry first. IANA's JSON Web Token Claims registry listed 163 claim names in its 28 October 2026 update, registered by standards such as OpenID Connect. If one of them means what you need, use it with that meaning. The example does that twice.
nameis OpenID Connect's "Full name".rolescomes from SCIM, the standard for user accounts, which defines it in RFC 7643 as "A list of roles for the user that collectively represent who the user is". RFC 9068, the standard for access tokens in JWT format, says that a sign-in service that puts a user's roles, groups or entitlements in an access token "SHOULD use" SCIM'sroles,groupsandentitlementsfor them. - Never give a registered name a meaning of your own. Libraries and services that know the registered meaning will read your claim that way.
scope, for example, is registered in RFC 8693 as "a JSON string containing a space-separated list of scopes", so ascopethat holds an array or anything else breaks the readers that expect the string. - Put everything else in a namespace you control. A URL on your own domain is the usual choice, as in
https://orders.example.com/plan: nobody else can make up a claim name under the orders API's own domain. The URL is only a name. Auth0's documentation, which recommends the same, says: "The namespace URL does not have to point to an actual resource. It is only used as an identifier; it will not be called."
A private name like plan is fine when one team controls every service that makes and reads the token, because that team can make sure nobody uses it for anything else. The cost of a URL name is its length: https://orders.example.com/plan takes 31 characters in every token's payload, where plan takes 4.
Check Every Claim Before You Trust It
An API reads custom claims to make decisions, so it has to be sure of them. Three things make sure:
- Verify the token first. Anyone can write any claim into a token they make themselves. Only a valid signature from a key you trust says the claims came from your sign-in service unchanged, as Decode vs Verify showed.
- Then check that each claim you use is there, with the type you expect. A valid signature doesn't promise either. An older version of the sign-in service may not have written the claim yet, another sign-in service may write it differently, and a mistake may change its type. Amazon Cognito's documentation gives the same advice for its own tokens: "Treat every other claim as optional and conditional on how the user authenticated." When a claim is missing or has the wrong type, deny the request.
- Ignore the claims you don't use. Section 4 of RFC 7519 says that "all claims that are not understood by implementations MUST be ignored." A token can carry claims for other APIs, and the orders API doesn't fail because of them.
The type check matters more than it looks. In JavaScript, Python and Ruby, the usual way to ask whether a list contains customer also works on a string, where it searches the text instead. A token whose roles is the string "not-a-customer" passes that test in all three languages, as When a Claim Has the Wrong Type shows.
What Not to Put in a Claim
A claim is easy to add, so it's tempting to put everything in the token. Three kinds of data don't belong there:
- Anything private. The payload is only base64url-encoded, so anyone who holds the token can read every claim, as What Is a JWT? showed. Leave out passwords, keys and personal details the API doesn't need. Section 12 of RFC 7519 says: "Omitting privacy-sensitive information from a JWT is the simplest way of minimizing privacy issues."
- Anything big. Every claim travels with every request. Firebase Authentication refuses custom claims over 1000 bytes, and its documentation warns that claims used to store data "could cause performance issues because all authenticated requests always contain a Firebase ID token".
- Anything that must be current. A claim is a copy of what the sign-in service knew when it made the token. If Zara moves to a cheaper plan, the token she already has still says
prountil it expires. Firebase documents the same for its own tokens: new custom claims reach a user's token only when the user signs in again or the token is refreshed. Keep tokens short-lived, and look up what must be up to date.
Custom Claims in Real Sign-In Services
Custom claims aren't only for your own sign-in service. Here is how four well-known ones name theirs and what shape they give them, from each service's own documentation:
| Sign-in service | Claims you'll meet | What its documentation says |
|---|---|---|
| Microsoft Entra ID | roles, scp and name in access tokens | roles is an "Array of strings", scp is a "String, a space separated list of scopes", and name is for display: "Don't use this value to make authorization decisions." |
| Auth0 | The claims you add in an Action | Recommends namespaced names, and warns: "In case of collisions, the transaction won't fail, but your custom claim won't be added to your tokens." The custom claims can take up to 100 KB. |
| Firebase Authentication | The claims you set with the Admin SDK | "The payload must not exceed 1000 bytes." New claims reach a user's ID token at the next sign-in or token refresh. |
| Amazon Cognito | cognito:groups and custom: attributes in ID tokens | cognito:groups "is always an array, even when the user belongs to a single group". Custom attributes are "always prefixed with custom:", and Cognito writes their values "as strings regardless of attribute type". |
The same Entra token carries one list as an array, roles, and another as a single space-separated string, scp. Cognito writes a number attribute as a string. An API has to know the shape of every claim it reads, and check it.
The Example
The program plays both parts, as in Registered Claims:
- The sign-in service,
https://auth.example.com, makes tokens with five registered claims,iss,sub,aud,iatand anexp15 minutes later, and three custom ones:name,rolesand the plan, under the claim namehttps://orders.example.com/plan. - The orders API,
https://orders.example.com, verifies each token as in Registered Claims: the signature, the algorithm, the times, the issuer and the audience. Then it applies one rule to each order: a customer may order up to their plan's limit. Before it uses a claim, it checks that the claim is there and has the type the rule needs.
The sign-in service makes three tokens:
- Zara's token: user
user-42, the rolescustomerandbeta-tester, and theproplan with an order limit of 500. - Sam's token: user
user-7, who works in support, with the rolesupportand no plan. - Zara's old token: the same user and roles, but made by the sign-in service's previous version, before it added plans. It has no plan claim.
The program prints Zara's token and its custom claims, then places four orders: Zara orders 120 and then 900, Sam orders 120, and Zara's old token orders 120.
Prerequisites
- The tools for your language. Pick its tab and check them. These are the versions this tutorial was run with:
- Node.js
- Python
- C#
- Java
- Go
- PHP
- Ruby
- Rust
uv, which also installs Python 3.15 for the project when your computer doesn't have it:
uv --version
uv 0.13.10 (e3e7c1eac 2026-11-24 aarch64-apple-darwin)
A Java 25 JDK and Maven:
java --version
mvn --version
openjdk 25.0.5.1 2026-11-17
OpenJDK Runtime Environment Homebrew (build 25.0.5.1)
OpenJDK 64-Bit Server VM Homebrew (build 25.0.5.1, mixed mode, sharing)
Apache Maven 3.10.2 (61b8bc355f4c4325463c22aa9afe4e7811a290f8)
…
php --version
composer --version
PHP 8.6.0 (cli) (built: Nov 17 2026 14:21:54) (NTS)
Copyright © The PHP Group and Contributors
Built by Homebrew
Zend Engine v4.6.0, Copyright © Zend by Perforce
with Zend OPcache v8.6.0, Copyright ©, by Zend by Perforce
Composer version 2.11.3 2026-11-24 10:14:18
PHP version 8.6.0 (/opt/homebrew/Cellar/php/8.6.0/bin/php)
Run the "diagnose" command to get more detailed diagnostics output.
Ruby 4.0, which comes with Bundler:
ruby --version
bundle --version
ruby 4.0.10 (2026-11-19 revision a704b7cd95) +PRISM [arm64-darwin25]
4.1.0
Rust, installed with rustup, which comes with Cargo:
cargo --version
cargo 1.100.1 (3acc79c0c 2026-11-05)
Step 1: Create a Project and Add the JWT Library
Each project lives in its own folder. Where a tab starts with mkdir custom-claims and cd custom-claims, those two commands create the folder and move into it. The other tools create the folder themselves. The commands are the same in every terminal, including PowerShell.
- Node.js
- Python
- C#
- Java
- Go
- PHP
- Ruby
- Rust
mkdir custom-claims
cd custom-claims
npm init -y
npm pkg set type=module
npm install jose
npm init -ycreates apackage.json, the file that describes a Node.js project, without asking any questions.npm pkg set type=modulemakes the project use ES modules, so the code can load jose withimport. npm 12 writes"type": "commonjs"into a newpackage.json, as the output shows.npm install josedownloads jose into anode_modulesfolder and adds it topackage.json.
Wrote to /Users/Shared/you/custom-claims/package.json:
{
"name": "custom-claims",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"type": "commonjs"
}
added 1 package, and audited 2 packages in 1s
1 package is looking for funding
run `npm fund` for details
found 0 vulnerabilities
package.json now says the project is a module and depends on jose:
{
"name": "custom-claims",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"type": "module",
"dependencies": {
"jose": "^6.2.19"
}
}
uv init --no-package custom-claims
cd custom-claims
uv add pyjwt
uv init --no-package custom-claimscreates the project in a newcustom-claimsfolder.--no-packagemakes it a plain folder with amain.py, the simplest layout for a one-file program.uv add pyjwtinstalls PyJWT into the project's.venvand records it inpyproject.toml. The package is called PyJWT, but your code imports it asjwt.
Initialized project `custom-claims` at `/Users/Shared/you/custom-claims`
Using CPython 3.15.2 interpreter at: /Library/Frameworks/Python.framework/Versions/3.15/bin/python3.15
Creating virtual environment at: .venv
Resolved 2 packages in 520ms
Prepared 1 package in 194ms
Installed 1 package in 3ms
+ pyjwt==2.15.1
dotnet new console -o custom-claims
cd custom-claims
dotnet package add Microsoft.IdentityModel.JsonWebTokens
dotnet new console -o custom-claimscreates a console app in a newcustom-claimsfolder.dotnet package addadds the NuGet package that holdsJsonWebTokenHandler, along with the packages it needs.
An issue was encountered verifying workloads. For more information, run "dotnet workload update".
The template "Console App" was created successfully.
Processing post-creation actions...
Restoring /Users/Shared/you/custom-claims/custom-claims.csproj:
Restore succeeded.
info : X.509 certificate chain validation will use the fallback certificate bundle at '/usr/local/share/dotnet/sdk/10.0.404/trustedroots/codesignctl.pem'.
info : X.509 certificate chain validation will use the fallback certificate bundle at '/usr/local/share/dotnet/sdk/10.0.404/trustedroots/timestampctl.pem'.
…
info : Package 'Microsoft.IdentityModel.JsonWebTokens' is compatible with all the specified frameworks in project '/Users/Shared/you/custom-claims/custom-claims.csproj'.
info : PackageReference for package 'Microsoft.IdentityModel.JsonWebTokens' version '8.25.0' added to file '/Users/Shared/you/custom-claims/custom-claims.csproj'.
info : Generating MSBuild file /Users/Shared/you/custom-claims/obj/custom-claims.csproj.nuget.g.targets.
info : Writing assets file to disk. Path: /Users/Shared/you/custom-claims/obj/project.assets.json
log : Restored /Users/Shared/you/custom-claims/custom-claims.csproj (in 2.83 sec).
The first line appears only when this is the first dotnet command under your user account. It's harmless, and Fixed: An issue was encountered verifying workloads explains why it appears and how to turn it off. The … stands for 46 lines in which NuGet downloads each package.
mkdir custom-claims
cd custom-claims
Maven, Java's build tool, reads a project from a file named pom.xml. Create it in the custom-claims folder with this content (how to write one from scratch):
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>custom-claims</artifactId>
<version>1.0.0</version>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jjwt.version>0.13.0</jjwt.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- jjwt-jackson asks for Jackson 2.12.7.1. This makes Maven use the newest Jackson 2 instead. -->
<dependency>
<groupId>com.fasterxml.jackson</groupId>
<artifactId>jackson-bom</artifactId>
<version>2.23.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>${jjwt.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>${jjwt.version}</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<mainClass>com.example.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
maven.compiler.releasecompiles for Java 25.- jjwt comes in three parts:
jjwt-apiis what your code calls, andjjwt-implandjjwt-jacksondo the work while the program runs, which is why theirscopeisruntime. jjwt-jacksonreads and writes JSON with Jackson, and on its own it asks for Jackson 2.12.7.1 from 2022, which has 11 published security advisories on OSV.dev. Thejackson-bomentry independencyManagementmakes Maven use Jackson 2.23.0 instead, the newest Jackson 2 release.exec-maven-pluginnames the class to run, so one Maven command runs the program in Step 6.
Check which Jackson version Maven picked. mvn dependency:tree prints every library the project uses, and -ntp leaves out the download progress:
mvn -ntp dependency:tree
[INFO] Scanning for projects...
[INFO] Loaded 24726 auto-discovered prefixes for remote repository central (prefixes-central.txt)
[INFO]
[INFO] ---------------------< com.example:custom-claims >----------------------
[INFO] Building custom-claims 1.0.0
[INFO] from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- dependency:3.11.0:tree (default-cli) @ custom-claims ---
[INFO] com.example:custom-claims:jar:1.0.0
[INFO] +- io.jsonwebtoken:jjwt-api:jar:0.13.0:compile
[INFO] +- io.jsonwebtoken:jjwt-impl:jar:0.13.0:runtime
[INFO] \- io.jsonwebtoken:jjwt-jackson:jar:0.13.0:runtime
[INFO] \- com.fasterxml.jackson.core:jackson-databind:jar:2.23.0:runtime
[INFO] +- com.fasterxml.jackson.core:jackson-annotations:jar:2.23:runtime
[INFO] \- com.fasterxml.jackson.core:jackson-core:jar:2.23.0:runtime
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 10.632 s
[INFO] Finished at: 2026-12-03T07:53:33Z
[INFO] ------------------------------------------------------------------------
jackson-databind:jar:2.23.0 is the version the jackson-bom entry asked for.
mkdir custom-claims
cd custom-claims
go mod init example.com/custom-claims
go get github.com/golang-jwt/jwt/v5
go mod init example.com/custom-claimscreates ago.modthat names the module.go get github.com/golang-jwt/jwt/v5adds golang-jwt to it.
go: creating new go.mod: module example.com/custom-claims
go: downloading github.com/golang-jwt/jwt/v5 v5.4.0
go: downloading github.com/golang-jwt/jwt v3.2.2+incompatible
go: added github.com/golang-jwt/jwt/v5 v5.4.0
Go also downloaded github.com/golang-jwt/jwt v3.2.2+incompatible, an older module, even though you asked for v5. To find which module holds a package, Go looks up every module path the package path could belong to, and the shorter path without /v5 is one of them. It only adds v5 to go.mod. There, v5 is marked // indirect until your code imports it.
mkdir custom-claims
cd custom-claims
composer require firebase/php-jwt
composer require creates composer.json, downloads php-jwt into a vendor folder and writes vendor/autoload.php, the one file your code loads to use it. The project now lives at googleapis/php-jwt on GitHub, but its Composer name is still firebase/php-jwt.
./composer.json has been created
Running composer update firebase/php-jwt
Loading composer repositories with package information
Updating dependencies
Lock file operations: 1 install, 0 updates, 0 removals
- Locking firebase/php-jwt (v7.2.2)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
- Downloading firebase/php-jwt (v7.2.2)
- Installing firebase/php-jwt (v7.2.2): Extracting archive
2 package suggestions were added by new dependencies, use `composer suggest` to see details.
Generating autoload files
No security vulnerability advisories found.
Using version ^7.2 for firebase/php-jwt
mkdir custom-claims
cd custom-claims
bundle init
bundle add jwt
bundle initcreates an emptyGemfile, the list of gems the project uses.bundle add jwtadds the jwt gem to it and installs it.
Writing new Gemfile to /Users/Shared/you/custom-claims/Gemfile
Fetching gem metadata from https://rubygems.org/....
Resolving dependencies...
Fetching gem metadata from https://rubygems.org/....
Fetching jwt 3.3.2
Installing jwt 3.3.2
cargo new custom-claims
cd custom-claims
cargo add jsonwebtoken --features rust_crypto
cargo add serde --features derive
cargo new custom-claimscreates the project with asrc/main.rs.jsonwebtoken12 does no cryptography of its own until you pick a backend. Its README says to enableaws_lc_rsorrust_crypto, andrust_cryptois written in pure Rust, so it builds anywhere without a C compiler.--featuresturns it on.serdewithderivelets the code turn its claims struct into JSON and back.
Creating binary (application) `custom-claims` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Updating crates.io index
Adding jsonwebtoken v12.0.0 to dependencies
Features:
+ rust_crypto
+ use_pem
- aws_lc_rs
Updating crates.io index
Locking 91 packages to highest Rust 1.100.1 compatible versions
Updating crates.io index
Adding serde v1.0.229 to dependencies
Features:
+ derive
+ serde_derive
+ std
- alloc
- rc
- unstable
Step 2: Give the Program a Secret
Every service in this example uses the same secret: 32 random bytes, the size RFC 7518 requires for HS256. The program reads it from an environment variable named JWT_SECRET, so the secret never sits in the code. How to Generate a Secret Key for HS256 JWTs in the Terminal explains the command, and How to Set an Environment Variable in the Terminal explains the variable.
- macOS / Linux
- Windows (PowerShell)
export JWT_SECRET=$(openssl rand -base64 32)
echo ${#JWT_SECRET}
44

$env:JWT_SECRET = [Convert]::ToBase64String([Security.Cryptography.RandomNumberGenerator]::GetBytes(32))
$env:JWT_SECRET.Length
44

JWT_SECRET now holds the 32 bytes as 44 characters of base64 text, and the program decodes that text back into the 32 bytes it uses as the key. The length check confirms the variable is set without printing the secret on your screen. The variable lasts until you close this terminal, so run the program from the same window.
Step 3: Write the Code That Adds Custom Claims
Create the program's file: main.js, main.py, Program.cs, src/main/java/com/example/Main.java, main.go, main.php, main.rb or src/main.rs, depending on your language. Most editors create the folders in the path for you. In Python, C# and Rust, replace what the template put in the file. The code goes in over the next three steps, and the complete file shows it all together.
The file starts with three constants: the issuer and the audience the orders API trusts, as in Registered Claims, and PLAN_CLAIM, the plan claim's name. Then comes the sign-in service's function. It takes the key, a user ID, a name, a list of roles and a plan, and returns a token with the registered claims and the custom ones. A user without a plan gets no plan claim at all.
- Node.js
- Python
- C#
- Java
- Go
- PHP
- Ruby
- Rust
import { SignJWT, jwtVerify, errors } from 'jose';
const ISSUER = 'https://auth.example.com';
const ORDERS_API = 'https://orders.example.com';
// A custom claim name on the orders API's own domain, so nobody else's claim can have it.
const PLAN_CLAIM = 'https://orders.example.com/plan';
// The sign-in service's job: the registered claims plus the custom claims the orders API needs.
async function createToken(key, userId, name, roles, plan) {
const claims = {
name, // a string
roles, // an array of strings
};
if (plan) {
claims[PLAN_CLAIM] = plan; // an object: the plan's name and its order limit
}
const now = Math.floor(Date.now() / 1000);
return new SignJWT(claims)
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.setIssuer(ISSUER)
.setSubject(userId)
.setAudience(ORDERS_API)
.setIssuedAt(now)
.setExpirationTime(now + 15 * 60)
.sign(key);
}
{ name, roles }is short for{ name: name, roles: roles }, so each claim takes the name of its variable.- The plan claim's name is a URL, which can't be written after a dot, so
claims[PLAN_CLAIM] = planadds it with square brackets.if (plan)skips it when the plan isnull. new SignJWT(claims)starts the payload with the custom claims, and thesetmethods add the registered ones. jose writes each value as JSON: the roles become an array and the plan an object.
import base64
import os
import sys
from datetime import datetime, timedelta, timezone
import jwt
ISSUER = "https://auth.example.com"
ORDERS_API = "https://orders.example.com"
# A custom claim name on the orders API's own domain, so nobody else's claim can have it.
PLAN_CLAIM = "https://orders.example.com/plan"
def create_token(key: bytes, user_id: str, name: str, roles: list[str], plan: dict | None) -> str:
"""The sign-in service's job: the registered claims plus the custom claims the orders API needs."""
now = datetime.now(tz=timezone.utc)
payload = {
"iss": ISSUER,
"sub": user_id,
"aud": ORDERS_API,
"iat": now,
"exp": now + timedelta(minutes=15),
"name": name, # a string
"roles": roles, # a list of strings
}
if plan is not None:
payload[PLAN_CLAIM] = plan # a dictionary: the plan's name and its order limit
return jwt.encode(payload, key, algorithm="HS256")
- The custom claims are more keys in the same payload dictionary as the registered ones. PyJWT writes the list of roles as a JSON array and the plan's dictionary as a JSON object.
plan: dict | Nonesays the function takes a dictionary orNone, andif plan is not Noneadds the plan claim only for a user who has a plan.
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
const string Issuer = "https://auth.example.com";
const string OrdersApi = "https://orders.example.com";
// A custom claim name on the orders API's own domain, so nobody else's claim can have it.
const string PlanClaim = "https://orders.example.com/plan";
// The sign-in service's job: the registered claims plus the custom claims the orders API needs.
static string CreateToken(byte[] key, string userId, string name, string[] roles, Dictionary<string, object>? plan)
{
var claims = new Dictionary<string, object>
{
["sub"] = userId,
["name"] = name, // a string
["roles"] = roles, // an array of strings
};
if (plan is not null)
{
claims[PlanClaim] = plan; // an object: the plan's name and its order limit
}
var now = DateTime.UtcNow;
var descriptor = new SecurityTokenDescriptor
{
Issuer = Issuer,
Audience = OrdersApi,
IssuedAt = now,
Expires = now.AddMinutes(15),
Claims = claims,
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256),
};
return new JsonWebTokenHandler().CreateToken(descriptor);
}
- The custom claims go in the descriptor's
Claimsdictionary, next tosub. IdentityModel writes astring[]as a JSON array and aDictionary<string, object>as a JSON object. - The plan is a dictionary because IdentityModel can't write an object of a class or record of your own. It stops with IDX11025: Cannot serialize object of type instead.
- The
?inDictionary<string, object>?says the plan may benull, andif (plan is not null)adds the claim only when there is one. - This function goes at the end of
Program.cs, after the code from Step 5, where the complete file has it.
package com.example;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.crypto.SecretKey;
public class Main {
static final String ISSUER = "https://auth.example.com";
static final String ORDERS_API = "https://orders.example.com";
// A custom claim name on the orders API's own domain, so nobody else's claim can have it.
static final String PLAN_CLAIM = "https://orders.example.com/plan";
// The sign-in service's job: the registered claims plus the custom claims the orders API needs.
static String createToken(SecretKey key, String userId, String name, List<String> roles,
Map<String, Object> plan) {
Instant now = Instant.now();
return Jwts.builder()
.issuer(ISSUER)
.subject(userId)
.audience().add(ORDERS_API).and()
.issuedAt(Date.from(now))
.expiration(Date.from(now.plus(Duration.ofMinutes(15))))
.claim("name", name) // a string
.claim("roles", roles) // an array of strings
.claim(PLAN_CLAIM, plan) // an object: the plan's name and its order limit; null leaves it out
.signWith(key, Jwts.SIG.HS256)
.compact();
}
.claim(name, value)adds one custom claim. Jackson, the JSON library jjwt uses here, writes aListas a JSON array and aMapas a JSON object.- A
nullvalue leaves the claim out, so a user without a plan gets no plan claim. jjwt's documentation forclaimsays that "A null or empty value will remove the claim entirely", but jjwt keeps an empty custom claim: an empty string, list or map stays in the token.
package main
import (
"encoding/base64"
"fmt"
"os"
"slices"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
)
const (
issuer = "https://auth.example.com"
ordersAPI = "https://orders.example.com"
)
// Plan is the value of the plan claim: a JSON object.
type Plan struct {
Name string `json:"name"`
OrderLimit int `json:"order_limit"`
}
// OrderClaims is the token's payload: the custom claims plus the registered ones.
// The plan claim's name is on the orders API's own domain, so nobody else's claim can have it.
type OrderClaims struct {
Name string `json:"name"` // a string
Roles []string `json:"roles"` // an array of strings
Plan *Plan `json:"https://orders.example.com/plan,omitempty"` // an object, left out when nil
jwt.RegisteredClaims
}
// createToken does the sign-in service's job: the registered claims plus
// the custom claims the orders API needs.
func createToken(key []byte, userID, name string, roles []string, plan *Plan) (string, error) {
now := time.Now()
claims := OrderClaims{
Name: name,
Roles: roles,
Plan: plan,
RegisteredClaims: jwt.RegisteredClaims{
Issuer: issuer,
Subject: userID,
Audience: jwt.ClaimStrings{ordersAPI},
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(15 * time.Minute)),
},
}
return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(key)
}
Plandescribes the plan object, andOrderClaimsthe whole payload: the three custom claims, withjwt.RegisteredClaimsembedded for the registered ones. Embedding makes its fields part ofOrderClaims.- Each struct tag gives a field its claim name. Go's
encoding/jsonaccepts a name made of "Unicode letters, digits, and ASCII punctuation except quotation marks, backslash, and comma", so a URL works too.omitemptyleaves the plan out when the pointer isnil. - The plan is a pointer,
*Plan, so that a user can have no plan at all:nil.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
const ISSUER = 'https://auth.example.com';
const ORDERS_API = 'https://orders.example.com';
// A custom claim name on the orders API's own domain, so nobody else's claim can have it.
const PLAN_CLAIM = 'https://orders.example.com/plan';
// The sign-in service's job: the registered claims plus the custom claims the orders API needs.
function createToken(string $key, string $userId, string $name, array $roles, ?array $plan): string
{
$now = time();
$payload = [
'iss' => ISSUER,
'sub' => $userId,
'aud' => ORDERS_API,
'iat' => $now,
'exp' => $now + 15 * 60,
'name' => $name, // a string
'roles' => $roles, // an array of strings
];
if ($plan !== null) {
$payload[PLAN_CLAIM] = $plan; // an object: the plan's name and its order limit
}
return JWT::encode($payload, $key, 'HS256');
}
- The custom claims are more keys in the payload array. php-jwt writes an array with named keys, like the plan, as a JSON object, and a list, like the roles, as a JSON array.
?array $plantakes an array ornull, and the plan claim is added only when there is a plan.
require 'jwt'
ISSUER = 'https://auth.example.com'
ORDERS_API = 'https://orders.example.com'
# A custom claim name on the orders API's own domain, so nobody else's claim can have it.
PLAN_CLAIM = 'https://orders.example.com/plan'
# The sign-in service's job: the registered claims plus the custom claims the orders API needs.
def create_token(key, user_id, name, roles, plan)
now = Time.now.to_i
payload = {
'iss' => ISSUER,
'sub' => user_id,
'aud' => ORDERS_API,
'iat' => now,
'exp' => now + (15 * 60),
'name' => name, # a string
'roles' => roles # an array of strings
}
payload[PLAN_CLAIM] = plan if plan # a hash: the plan's name and its order limit
JWT.encode(payload, key, 'HS256')
end
- The custom claims are more keys in the payload hash. ruby-jwt writes an array as a JSON array and a hash as a JSON object.
payload[PLAN_CLAIM] = plan if planadds the plan claim only when there is a plan, becausenilcounts as false.
use std::time::{SystemTime, UNIX_EPOCH};
use jsonwebtoken::errors::Error;
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
use serde::{Deserialize, Serialize};
const ISSUER: &str = "https://auth.example.com";
const ORDERS_API: &str = "https://orders.example.com";
/// The value of the plan claim: a JSON object.
#[derive(Debug, Serialize, Deserialize)]
struct Plan {
name: String,
order_limit: u32,
}
/// The token's payload: the registered claims plus the custom ones.
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
iss: String,
sub: String,
aud: String,
iat: u64,
exp: u64,
name: String, // a string
roles: Vec<String>, // an array of strings
// An object, named with a URL on the orders API's own domain so nobody else's
// claim can have it, and left out of the token when there's no plan.
#[serde(
rename = "https://orders.example.com/plan",
skip_serializing_if = "Option::is_none"
)]
plan: Option<Plan>,
}
/// The sign-in service's job: the registered claims plus the custom claims the orders API needs.
fn create_token(
key: &EncodingKey,
user_id: &str,
name: &str,
roles: &[&str],
plan: Option<Plan>,
) -> Result<String, Error> {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("the clock is set before 1970")
.as_secs();
let claims = Claims {
iss: ISSUER.to_owned(),
sub: user_id.to_owned(),
aud: ORDERS_API.to_owned(),
iat: now,
exp: now + 15 * 60,
name: name.to_owned(),
roles: roles.iter().map(|role| role.to_string()).collect(),
plan,
};
encode(&Header::new(Algorithm::HS256), &claims, key)
}
Plandescribes the plan object, andClaimsthe whole payload. serde writes each field as a claim with the field's name.renamegives the plan field a JSON name that a Rust field name can't have.Option<Plan>lets the plan be missing,None.skip_serializing_if = "Option::is_none"leaves the claim out in that case. Without it, serde would write the claim with the valuenull.roles.iter().map(|role| role.to_string()).collect()turns the&strroles into theStrings the struct holds.
Step 4: Verify the Token and Read Its Custom Claims
The orders API verifies a token exactly as in Registered Claims: the signature with the shared key, only HS256, the times, the issuer and the audience. The second function prints the custom claims of a verified token. It reads each claim by its name, in the form the library hands it back. It's only used for Zara's token, which the program made itself with all three claims, so it doesn't check them. The orders API's rule in Step 5 does.
- Node.js
- Python
- C#
- Java
- Go
- PHP
- Ruby
- Rust
// The orders API's check: the signature and the times, then the issuer and audience.
async function verifyForOrders(key, token) {
const { payload } = await jwtVerify(token, key, {
algorithms: ['HS256'],
issuer: ISSUER,
audience: ORDERS_API,
});
return payload;
}
// Print the custom claims of a verified token.
function showClaims(claims) {
const plan = claims[PLAN_CLAIM];
console.log(` name: ${claims.name}`);
console.log(` roles: ${claims.roles.join(', ')}`);
console.log(` plan: ${plan.name}, order limit ${plan.order_limit}`);
}
jwtVerifyreturns the payload as a plain JavaScript object:claims.name,claims.roles, andclaims[PLAN_CLAIM]for the name that's a URL.rolescomes back as an array, andjoin(', ')prints its items with a comma between them.
def verify_for_orders(key: bytes, token: str) -> dict:
"""The orders API's check: the signature and the times, then the issuer and audience."""
return jwt.decode(token, key, algorithms=["HS256"], issuer=ISSUER, audience=ORDERS_API)
def show_claims(claims: dict) -> None:
"""Print the custom claims of a verified token."""
plan = claims[PLAN_CLAIM]
print(f" name: {claims['name']}")
print(f" roles: {', '.join(claims['roles'])}")
print(f" plan: {plan['name']}, order limit {plan['order_limit']}")
jwt.decodereturns the payload as a dictionary. The roles come back as a list and the plan as a dictionary.', '.join(...)prints the roles with a comma between them.
// The orders API's check: the signature and the times, then the issuer and audience.
static async Task<JsonWebToken> VerifyForOrdersAsync(byte[] key, string token)
{
var parameters = new TokenValidationParameters
{
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidAlgorithms = [SecurityAlgorithms.HmacSha256],
ValidIssuer = Issuer,
ValidAudience = OrdersApi,
};
var result = await new JsonWebTokenHandler().ValidateTokenAsync(token, parameters);
if (!result.IsValid)
{
throw result.Exception;
}
return (JsonWebToken)result.SecurityToken;
}
// Print the custom claims of a verified token.
static void ShowClaims(JsonWebToken token)
{
var plan = token.GetPayloadValue<Dictionary<string, object>>(PlanClaim);
Console.WriteLine($" name: {token.GetPayloadValue<string>("name")}");
Console.WriteLine($" roles: {string.Join(", ", token.GetPayloadValue<string[]>("roles"))}");
Console.WriteLine($" plan: {plan["name"]}, order limit {plan["order_limit"]}");
}
- The validated token is a
JsonWebToken, andGetPayloadValue<T>reads one claim as the type you name: astring, astring[]or aDictionary<string, object>. GetPayloadValuethrows when the token doesn't have the claim, which is why Step 5 usesTryGetPayloadValue.
// The orders API's check: the signature and the times, then the issuer and audience.
static Claims verifyForOrders(SecretKey key, String token) {
return Jwts.parser()
.verifyWith(key)
.requireIssuer(ISSUER)
.requireAudience(ORDERS_API)
.build()
.parseSignedClaims(token)
.getPayload();
}
// Print the custom claims of a verified token.
static void showClaims(Claims claims) {
Map<?, ?> plan = claims.get(PLAN_CLAIM, Map.class);
System.out.println(" name: " + claims.get("name", String.class));
System.out.println(" roles: " + claims.get("roles", List.class));
System.out.println(" plan: " + plan.get("name") + ", order limit " + plan.get("order_limit"));
}
getPayload()returns the claims asClaims, a map from claim names to values.claims.get(name, type)returns one claim as that type.- Jackson read the roles as a
Listand the plan as aMap. Printing aListshows its items in brackets.
// verifyForOrders is the orders API's check: the signature and the times,
// then the issuer and audience.
func verifyForOrders(key []byte, token string) (*OrderClaims, error) {
claims := &OrderClaims{}
_, err := jwt.ParseWithClaims(token, claims, func(*jwt.Token) (any, error) {
return key, nil
},
jwt.WithValidMethods([]string{"HS256"}),
jwt.WithIssuer(issuer),
jwt.WithAudience(ordersAPI),
)
if err != nil {
return nil, err
}
return claims, nil
}
// showClaims prints the custom claims of a verified token.
func showClaims(claims *OrderClaims) {
fmt.Printf(" name: %s\n", claims.Name)
fmt.Printf(" roles: %s\n", strings.Join(claims.Roles, ", "))
fmt.Printf(" plan: %s, order limit %d\n", claims.Plan.Name, claims.Plan.OrderLimit)
}
ParseWithClaimsfills theOrderClaimsstruct, so the claims are fields:claims.Name,claims.Rolesandclaims.Plan.strings.Joinprints the roles with a comma between them.
// The orders API's check: the signature and the times, then the issuer and audience.
// php-jwt checks the signature, exp, nbf and iat itself, but not iss or aud,
// so this function checks those two.
function verifyForOrders(string $key, string $token): stdClass
{
$claims = JWT::decode($token, new Key($key, 'HS256'));
if (($claims->iss ?? null) !== ISSUER) {
throw new UnexpectedValueException('Invalid issuer');
}
// aud can be one string or an array of strings, so turn it into an array first.
$audiences = (array) ($claims->aud ?? []);
if (!in_array(ORDERS_API, $audiences, true)) {
throw new UnexpectedValueException('Invalid audience');
}
return $claims;
}
// Print the custom claims of a verified token.
function showClaims(stdClass $claims): void
{
$plan = $claims->{PLAN_CLAIM};
echo " name: {$claims->name}\n";
echo ' roles: ' . implode(', ', $claims->roles) . "\n";
echo " plan: {$plan->name}, order limit {$plan->order_limit}\n";
}
JWT::decodereturns the payload as astdClassobject, and the plan inside it is astdClassobject too.$claims->{PLAN_CLAIM}reads a property whose name is in a constant, which works for a name like a URL.implode(', ', ...)prints the roles with a comma between them.
# The orders API's check: the signature and the times, then the issuer and audience.
def verify_for_orders(key, token)
claims, _header = JWT.decode(token, key, true,
algorithm: 'HS256',
iss: ISSUER, verify_iss: true,
aud: ORDERS_API, verify_aud: true)
claims
end
# Print the custom claims of a verified token.
def show_claims(claims)
plan = claims[PLAN_CLAIM]
puts " name: #{claims['name']}"
puts " roles: #{claims['roles'].join(', ')}"
puts " plan: #{plan['name']}, order limit #{plan['order_limit']}"
end
JWT.decodereturns the payload as a hash with string keys. The roles come back as anArrayand the plan as aHash.join(', ')prints the roles with a comma between them.
/// The orders API's check: the signature and the times, then the issuer and audience.
fn verify_for_orders(key: &DecodingKey, token: &str) -> Result<Claims, Error> {
let mut validation = Validation::new(Algorithm::HS256);
validation.set_issuer(&[ISSUER]);
validation.set_audience(&[ORDERS_API]);
// Reject tokens that leave out exp, iss or aud.
validation.set_required_spec_claims(&["exp", "iss", "aud"]);
let data = decode::<Claims>(token, key, &validation)?;
Ok(data.claims)
}
/// Print the custom claims of a verified token.
fn show_claims(claims: &Claims) {
println!(" name: {}", claims.name);
println!(" roles: {}", claims.roles.join(", "));
if let Some(plan) = &claims.plan {
println!(" plan: {}, order limit {}", plan.name, plan.order_limit);
}
}
decode::<Claims>fills theClaimsstruct, so the claims are fields.if let Some(plan)prints the plan only when the token has one.
Step 5: Check the Claims, Then Decide
Now the orders API's rule: a customer may order up to their plan's limit. Before the rule uses a claim, it checks that the claim is there and has the type the rule needs, and it denies the order when it doesn't. That way, a missing claim or a wrong type can never let an order through by accident. Then report prints the decision for one order, and the last part makes the three tokens and places the four orders:
- Node.js
- Python
- C#
- Java
- Go
- PHP
- Ruby
- Rust
// The orders API's rule: a customer may order up to their plan's limit.
// A valid signature proves who wrote the claims, not that each one is there
// with the type the rule expects, so the rule checks that first.
function checkOrder(claims, amount) {
const roles = claims.roles;
if (!Array.isArray(roles) || !roles.includes('customer')) {
return 'denied: needs the customer role';
}
const plan = claims[PLAN_CLAIM];
if (typeof plan !== 'object' || plan === null || !Number.isInteger(plan.order_limit)) {
return 'denied: the token has no plan';
}
if (amount > plan.order_limit) {
return `denied: over the ${plan.name} plan's order limit of ${plan.order_limit}`;
}
return 'allowed';
}
// Show what the orders API makes of one order.
async function report(key, label, token, amount) {
try {
const claims = await verifyForOrders(key, token);
console.log(`${label}: ${checkOrder(claims, amount)}`);
} catch (err) {
if (!(err instanceof errors.JOSEError)) throw err;
console.log(`${label}: rejected: ${err.message}`);
}
}
// The key every service shares: 32 random bytes, kept as base64 text in JWT_SECRET.
const secret = process.env.JWT_SECRET;
if (!secret) {
console.error('Set the JWT_SECRET environment variable first.');
process.exit(1);
}
const key = Uint8Array.fromBase64(secret);
const zara = await createToken(key, 'user-42', 'Zara', ['customer', 'beta-tester'], {
name: 'pro',
order_limit: 500,
});
const sam = await createToken(key, 'user-7', 'Sam', ['support'], null);
// A token from the sign-in service's previous version, which didn't add plans yet.
const old = await createToken(key, 'user-42', 'Zara', ['customer', 'beta-tester'], null);
console.log(`Zara's token: ${zara}`);
console.log("Custom claims in Zara's token:");
showClaims(await verifyForOrders(key, zara));
await report(key, 'Zara orders 120', zara, 120);
await report(key, 'Zara orders 900', zara, 900);
await report(key, 'Sam orders 120', sam, 120);
await report(key, "Zara's old token orders 120", old, 120);
Array.isArray(roles)is true only for an array, andincludes('customer')then looks for an item equal tocustomer.typeof plan !== 'object' || plan === nullturns away anything that isn't an object,nullincluded:typeof nullis'object'in JavaScript.Number.isIntegerchecks that the limit is a whole number.reportcatches jose's errors, which all extendJOSEError, and prints their message.
def check_order(claims: dict, amount: int) -> str:
"""The orders API's rule: a customer may order up to their plan's limit.
A valid signature proves who wrote the claims, not that each one is there
with the type the rule expects, so the rule checks that first.
"""
roles = claims.get("roles")
if not isinstance(roles, list) or "customer" not in roles:
return "denied: needs the customer role"
plan = claims.get(PLAN_CLAIM)
if not isinstance(plan, dict) or not isinstance(plan.get("order_limit"), int):
return "denied: the token has no plan"
if amount > plan["order_limit"]:
return f"denied: over the {plan['name']} plan's order limit of {plan['order_limit']}"
return "allowed"
def report(key: bytes, label: str, token: str, amount: int) -> None:
"""Show what the orders API makes of one order."""
try:
claims = verify_for_orders(key, token)
print(f"{label}: {check_order(claims, amount)}")
except jwt.InvalidTokenError as err:
print(f"{label}: rejected: {err}")
def main() -> None:
# The key every service shares: 32 random bytes, kept as base64 text in JWT_SECRET.
secret = os.environ.get("JWT_SECRET")
if not secret:
sys.exit("Set the JWT_SECRET environment variable first.")
key = base64.b64decode(secret, validate=True)
zara = create_token(key, "user-42", "Zara", ["customer", "beta-tester"], {"name": "pro", "order_limit": 500})
sam = create_token(key, "user-7", "Sam", ["support"], None)
# A token from the sign-in service's previous version, which didn't add plans yet.
old = create_token(key, "user-42", "Zara", ["customer", "beta-tester"], None)
print(f"Zara's token: {zara}")
print("Custom claims in Zara's token:")
show_claims(verify_for_orders(key, zara))
report(key, "Zara orders 120", zara, 120)
report(key, "Zara orders 900", zara, 900)
report(key, "Sam orders 120", sam, 120)
report(key, "Zara's old token orders 120", old, 120)
if __name__ == "__main__":
main()
claims.get("roles")returnsNonefor a missing claim, whereclaims["roles"]would raise aKeyError.isinstance(roles, list)andisinstance(plan, dict)check the types, andisinstance(plan.get("order_limit"), int)checks the limit.reportcatchesjwt.InvalidTokenError, which every PyJWT rejection extends.
// The key every service shares: 32 random bytes, kept as base64 text in JWT_SECRET.
var secret = Environment.GetEnvironmentVariable("JWT_SECRET");
if (string.IsNullOrEmpty(secret))
{
Console.Error.WriteLine("Set the JWT_SECRET environment variable first.");
return 1;
}
var key = Convert.FromBase64String(secret);
var zara = CreateToken(key, "user-42", "Zara", ["customer", "beta-tester"],
new Dictionary<string, object> { ["name"] = "pro", ["order_limit"] = 500 });
var sam = CreateToken(key, "user-7", "Sam", ["support"], null);
// A token from the sign-in service's previous version, which didn't add plans yet.
var old = CreateToken(key, "user-42", "Zara", ["customer", "beta-tester"], null);
Console.WriteLine($"Zara's token: {zara}");
Console.WriteLine("Custom claims in Zara's token:");
ShowClaims(await VerifyForOrdersAsync(key, zara));
await ReportAsync(key, "Zara orders 120", zara, 120);
await ReportAsync(key, "Zara orders 900", zara, 900);
await ReportAsync(key, "Sam orders 120", sam, 120);
await ReportAsync(key, "Zara's old token orders 120", old, 120);
return 0;
// The orders API's rule: a customer may order up to their plan's limit.
// A valid signature proves who wrote the claims, not that each one is there
// with the type the rule expects, so the rule checks that first.
static string CheckOrder(JsonWebToken token, int amount)
{
if (!token.TryGetPayloadValue<string[]>("roles", out var roles) || !roles.Contains("customer"))
{
return "denied: needs the customer role";
}
if (!token.TryGetPayloadValue<Dictionary<string, object>>(PlanClaim, out var plan)
|| plan.GetValueOrDefault("order_limit") is not int orderLimit)
{
return "denied: the token has no plan";
}
if (amount > orderLimit)
{
return $"denied: over the {plan["name"]} plan's order limit of {orderLimit}";
}
return "allowed";
}
// Show what the orders API makes of one order.
static async Task ReportAsync(byte[] key, string label, string token, int amount)
{
try
{
var verified = await VerifyForOrdersAsync(key, token);
Console.WriteLine($"{label}: {CheckOrder(verified, amount)}");
}
catch (SecurityTokenException ex)
{
// The exception's type names the check that failed; that's all this program shows.
Console.WriteLine($"{label}: rejected: {ex.GetType().Name}");
}
}
- The code at the top of
Program.csruns first, and the functions follow it.["customer", "beta-tester"]makes the array of roles. TryGetPayloadValue<T>returnsfalseinstead of throwing when the claim is missing or can't be read asT. One case still throws: a list that holds text, read asint[]orlong[]. Fixed: "The requested operation requires an element of type 'Number', but the target element has type 'String'" from TryGetPayloadValue in .NET C# shows it and the fix.plan.GetValueOrDefault("order_limit")returnsnullwhen the plan has no limit, andis not int orderLimitis true unless the value is anint. When it is one, it goes intoorderLimit.
// The orders API's rule: a customer may order up to their plan's limit.
// A valid signature proves who wrote the claims, not that each one is there
// with the type the rule expects, so the rule checks that first.
static String checkOrder(Claims claims, int amount) {
if (!(claims.get("roles") instanceof List<?> roles) || !roles.contains("customer")) {
return "denied: needs the customer role";
}
if (!(claims.get(PLAN_CLAIM) instanceof Map<?, ?> plan)
|| !(plan.get("order_limit") instanceof Integer orderLimit)) {
return "denied: the token has no plan";
}
if (amount > orderLimit) {
return "denied: over the " + plan.get("name") + " plan's order limit of " + orderLimit;
}
return "allowed";
}
// Show what the orders API makes of one order.
static void report(SecretKey key, String label, String token, int amount) {
try {
Claims claims = verifyForOrders(key, token);
System.out.println(label + ": " + checkOrder(claims, amount));
} catch (JwtException e) {
System.out.println(label + ": rejected: " + e.getMessage());
}
}
public static void main(String[] args) {
// The key every service shares: 32 random bytes, kept as base64 text in JWT_SECRET.
String secret = System.getenv("JWT_SECRET");
if (secret == null || secret.isEmpty()) {
System.err.println("Set the JWT_SECRET environment variable first.");
System.exit(1);
}
SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));
String zara = createToken(key, "user-42", "Zara", List.of("customer", "beta-tester"),
Map.of("name", "pro", "order_limit", 500));
String sam = createToken(key, "user-7", "Sam", List.of("support"), null);
// A token from the sign-in service's previous version, which didn't add plans yet.
String old = createToken(key, "user-42", "Zara", List.of("customer", "beta-tester"), null);
System.out.println("Zara's token: " + zara);
System.out.println("Custom claims in Zara's token:");
showClaims(verifyForOrders(key, zara));
report(key, "Zara orders 120", zara, 120);
report(key, "Zara orders 900", zara, 900);
report(key, "Sam orders 120", sam, 120);
report(key, "Zara's old token orders 120", old, 120);
}
}
instanceof List<?> roleschecks that the claim is a list and names itrolesin one step.<?>stands for "a list of something": the program doesn't assume what the items are.- Jackson reads a whole number that fits in an
intas anInteger, soinstanceof Integer orderLimitchecks the limit. List.of(...)andMap.of(...)make the roles and the plan, andnullstands for "no plan".
// checkOrder is the orders API's rule: a customer may order up to their plan's limit.
// ParseWithClaims already rejected a token whose claims don't fit the struct's types,
// but a claim the token leaves out is nil or empty, so the rule checks for that.
func checkOrder(claims *OrderClaims, amount int) string {
if !slices.Contains(claims.Roles, "customer") {
return "denied: needs the customer role"
}
if claims.Plan == nil {
return "denied: the token has no plan"
}
if amount > claims.Plan.OrderLimit {
return fmt.Sprintf("denied: over the %s plan's order limit of %d", claims.Plan.Name, claims.Plan.OrderLimit)
}
return "allowed"
}
// report shows what the orders API makes of one order.
func report(key []byte, label, token string, amount int) {
claims, err := verifyForOrders(key, token)
if err != nil {
fmt.Printf("%s: rejected: %v\n", label, err)
return
}
fmt.Printf("%s: %s\n", label, checkOrder(claims, amount))
}
// fail prints a message to standard error and stops the program.
func fail(a ...any) {
fmt.Fprintln(os.Stderr, a...)
os.Exit(1)
}
func main() {
// The key every service shares: 32 random bytes, kept as base64 text in JWT_SECRET.
secret := os.Getenv("JWT_SECRET")
if secret == "" {
fail("Set the JWT_SECRET environment variable first.")
}
key, err := base64.StdEncoding.DecodeString(secret)
if err != nil {
fail("JWT_SECRET is not valid base64:", err)
}
zara, err := createToken(key, "user-42", "Zara", []string{"customer", "beta-tester"},
&Plan{Name: "pro", OrderLimit: 500})
if err != nil {
fail("Could not create the token:", err)
}
sam, err := createToken(key, "user-7", "Sam", []string{"support"}, nil)
if err != nil {
fail("Could not create the token:", err)
}
// A token from the sign-in service's previous version, which didn't add plans yet.
old, err := createToken(key, "user-42", "Zara", []string{"customer", "beta-tester"}, nil)
if err != nil {
fail("Could not create the token:", err)
}
fmt.Printf("Zara's token: %s\n", zara)
fmt.Println("Custom claims in Zara's token:")
claims, err := verifyForOrders(key, zara)
if err != nil {
fail("Zara's token was rejected:", err)
}
showClaims(claims)
report(key, "Zara orders 120", zara, 120)
report(key, "Zara orders 900", zara, 900)
report(key, "Sam orders 120", sam, 120)
report(key, "Zara's old token orders 120", old, 120)
}
ParseWithClaimsalready rejected any token whose claims don't fit the struct's types. A claim the token leaves out keeps its zero value:nilforRolesand forPlan.slices.Containsis false for anilslice, andclaims.Plan == nilcatches the missing plan.fmt.Sprintfbuilds the message.
// The orders API's rule: a customer may order up to their plan's limit.
// A valid signature proves who wrote the claims, not that each one is there
// with the type the rule expects, so the rule checks that first.
function checkOrder(stdClass $claims, int $amount): string
{
$roles = $claims->roles ?? null;
if (!is_array($roles) || !in_array('customer', $roles, true)) {
return 'denied: needs the customer role';
}
$plan = $claims->{PLAN_CLAIM} ?? null;
if (!($plan instanceof stdClass) || !is_int($plan->order_limit ?? null)) {
return 'denied: the token has no plan';
}
if ($amount > $plan->order_limit) {
return "denied: over the {$plan->name} plan's order limit of {$plan->order_limit}";
}
return 'allowed';
}
// Show what the orders API makes of one order.
function report(string $key, string $label, string $token, int $amount): void
{
try {
$claims = verifyForOrders($key, $token);
echo "{$label}: " . checkOrder($claims, $amount) . "\n";
} catch (UnexpectedValueException $e) {
echo "{$label}: rejected: {$e->getMessage()}\n";
}
}
// The key every service shares: 32 random bytes, kept as base64 text in JWT_SECRET.
$secret = getenv('JWT_SECRET');
if ($secret === false || $secret === '') {
fwrite(STDERR, "Set the JWT_SECRET environment variable first.\n");
exit(1);
}
$key = base64_decode($secret, true);
if ($key === false) {
fwrite(STDERR, "JWT_SECRET is not valid base64.\n");
exit(1);
}
$zara = createToken($key, 'user-42', 'Zara', ['customer', 'beta-tester'], ['name' => 'pro', 'order_limit' => 500]);
$sam = createToken($key, 'user-7', 'Sam', ['support'], null);
// A token from the sign-in service's previous version, which didn't add plans yet.
$old = createToken($key, 'user-42', 'Zara', ['customer', 'beta-tester'], null);
echo "Zara's token: {$zara}\n";
echo "Custom claims in Zara's token:\n";
showClaims(verifyForOrders($key, $zara));
report($key, 'Zara orders 120', $zara, 120);
report($key, 'Zara orders 900', $zara, 900);
report($key, 'Sam orders 120', $sam, 120);
report($key, "Zara's old token orders 120", $old, 120);
?? nullgivesnullinstead of a warning when the token doesn't have the claim.is_array,instanceof stdClassandis_intcheck the types, andin_arraywithtruecompares the roles strictly.reportcatchesUnexpectedValueException, which covers php-jwt's rejections and the two thatverifyForOrdersthrows itself.
# The orders API's rule: a customer may order up to their plan's limit.
# A valid signature proves who wrote the claims, not that each one is there
# with the type the rule expects, so the rule checks that first.
def check_order(claims, amount)
roles = claims['roles']
return 'denied: needs the customer role' unless roles.is_a?(Array) && roles.include?('customer')
plan = claims[PLAN_CLAIM]
return 'denied: the token has no plan' unless plan.is_a?(Hash) && plan['order_limit'].is_a?(Integer)
if amount > plan['order_limit']
return "denied: over the #{plan['name']} plan's order limit of #{plan['order_limit']}"
end
'allowed'
end
# Show what the orders API makes of one order.
def report(key, label, token, amount)
claims = verify_for_orders(key, token)
puts "#{label}: #{check_order(claims, amount)}"
rescue JWT::DecodeError => e
puts "#{label}: rejected: #{e.message}"
end
# The key every service shares: 32 random bytes, kept as base64 text in JWT_SECRET.
secret = ENV.fetch('JWT_SECRET', '')
abort 'Set the JWT_SECRET environment variable first.' if secret.empty?
key = secret.unpack1('m0')
zara = create_token(key, 'user-42', 'Zara', %w[customer beta-tester], { 'name' => 'pro', 'order_limit' => 500 })
sam = create_token(key, 'user-7', 'Sam', %w[support], nil)
# A token from the sign-in service's previous version, which didn't add plans yet.
old = create_token(key, 'user-42', 'Zara', %w[customer beta-tester], nil)
puts "Zara's token: #{zara}"
puts "Custom claims in Zara's token:"
show_claims(verify_for_orders(key, zara))
report(key, 'Zara orders 120', zara, 120)
report(key, 'Zara orders 900', zara, 900)
report(key, 'Sam orders 120', sam, 120)
report(key, "Zara's old token orders 120", old, 120)
return ... unlessleaves the method early when the condition is false.is_a?(Array),is_a?(Hash)andis_a?(Integer)check the types, andinclude?('customer')looks for an item equal tocustomer.%w[customer beta-tester]is a short way to write an array of strings.
/// The orders API's rule: a customer may order up to their plan's limit.
/// decode already rejected a token whose claims don't fit the struct's types,
/// and a plan the token leaves out is None, so the rule checks for that.
fn check_order(claims: &Claims, amount: u32) -> String {
if !claims.roles.iter().any(|role| role == "customer") {
return "denied: needs the customer role".to_owned();
}
let Some(plan) = &claims.plan else {
return "denied: the token has no plan".to_owned();
};
if amount > plan.order_limit {
return format!(
"denied: over the {} plan's order limit of {}",
plan.name, plan.order_limit
);
}
"allowed".to_owned()
}
/// Show what the orders API makes of one order.
fn report(key: &DecodingKey, label: &str, token: &str, amount: u32) {
match verify_for_orders(key, token) {
Ok(claims) => println!("{label}: {}", check_order(&claims, amount)),
Err(err) => println!("{label}: rejected: {err}"),
}
}
fn main() -> Result<(), Error> {
// The key every service shares: 32 random bytes, kept as base64 text in JWT_SECRET.
let secret = std::env::var("JWT_SECRET").unwrap_or_default();
if secret.is_empty() {
eprintln!("Set the JWT_SECRET environment variable first.");
std::process::exit(1);
}
let encoding_key = EncodingKey::from_base64_secret(&secret)?;
let decoding_key = DecodingKey::from_base64_secret(&secret)?;
let pro = Plan {
name: "pro".to_owned(),
order_limit: 500,
};
let zara = create_token(
&encoding_key,
"user-42",
"Zara",
&["customer", "beta-tester"],
Some(pro),
)?;
let sam = create_token(&encoding_key, "user-7", "Sam", &["support"], None)?;
// A token from the sign-in service's previous version, which didn't add plans yet.
let old = create_token(
&encoding_key,
"user-42",
"Zara",
&["customer", "beta-tester"],
None,
)?;
println!("Zara's token: {zara}");
println!("Custom claims in Zara's token:");
show_claims(&verify_for_orders(&decoding_key, &zara)?);
report(&decoding_key, "Zara orders 120", &zara, 120);
report(&decoding_key, "Zara orders 900", &zara, 900);
report(&decoding_key, "Sam orders 120", &sam, 120);
report(&decoding_key, "Zara's old token orders 120", &old, 120);
Ok(())
}
decodealready rejected any token whose claims don't fit the struct's types.iter().any(|role| role == "customer")is true when any role equalscustomer, andlet Some(plan) = &claims.plan else { ... }leaves the function when the plan isNone.
Step 6: Run the Program
Run the program in the terminal where you set JWT_SECRET:
- Node.js
- Python
- C#
- Java
- Go
- PHP
- Ruby
- Rust
node main.js
Zara's token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiWmFyYSIsInJvbGVzIjpbImN1c3RvbWVyIiwiYmV0YS10ZXN0ZXIiXSwiaHR0cHM6Ly9vcmRlcnMuZXhhbXBsZS5jb20vcGxhbiI6eyJuYW1lIjoicHJvIiwib3JkZXJfbGltaXQiOjUwMH0sImlzcyI6Imh0dHBzOi8vYXV0aC5leGFtcGxlLmNvbSIsInN1YiI6InVzZXItNDIiLCJhdWQiOiJodHRwczovL29yZGVycy5leGFtcGxlLmNvbSIsImlhdCI6MTc5NjI4NDM0OSwiZXhwIjoxNzk2Mjg1MjQ5fQ.RNByZ-W9SAB1-x8Eg4E7kxl7clQzIkg5az1wUDjReRY
Custom claims in Zara's token:
name: Zara
roles: customer, beta-tester
plan: pro, order limit 500
Zara orders 120: allowed
Zara orders 900: denied: over the pro plan's order limit of 500
Sam orders 120: denied: needs the customer role
Zara's old token orders 120: denied: the token has no plan

uv run main.py
Zara's token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiJ1c2VyLTQyIiwiYXVkIjoiaHR0cHM6Ly9vcmRlcnMuZXhhbXBsZS5jb20iLCJpYXQiOjE3OTYyODQzNjMsImV4cCI6MTc5NjI4NTI2MywibmFtZSI6IlphcmEiLCJyb2xlcyI6WyJjdXN0b21lciIsImJldGEtdGVzdGVyIl0sImh0dHBzOi8vb3JkZXJzLmV4YW1wbGUuY29tL3BsYW4iOnsibmFtZSI6InBybyIsIm9yZGVyX2xpbWl0Ijo1MDB9fQ.e-3lGnSw7-04rvxWYijlOZD3Xgz2jXXmMO8a5xsH1nI
Custom claims in Zara's token:
name: Zara
roles: customer, beta-tester
plan: pro, order limit 500
Zara orders 120: allowed
Zara orders 900: denied: over the pro plan's order limit of 500
Sam orders 120: denied: needs the customer role
Zara's old token orders 120: denied: the token has no plan

dotnet run
Zara's token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJodHRwczovL29yZGVycy5leGFtcGxlLmNvbSIsImlzcyI6Imh0dHBzOi8vYXV0aC5leGFtcGxlLmNvbSIsImV4cCI6MTc5NjI4NTI4MywiaWF0IjoxNzk2Mjg0MzgzLCJzdWIiOiJ1c2VyLTQyIiwibmFtZSI6IlphcmEiLCJyb2xlcyI6WyJjdXN0b21lciIsImJldGEtdGVzdGVyIl0sImh0dHBzOi8vb3JkZXJzLmV4YW1wbGUuY29tL3BsYW4iOnsibmFtZSI6InBybyIsIm9yZGVyX2xpbWl0Ijo1MDB9LCJuYmYiOjE3OTYyODQzODN9.2ja1-7X0DPMFZKEzqKJ8HuDJ9AYPRFCgkVGJXptmhjE
Custom claims in Zara's token:
name: Zara
roles: customer, beta-tester
plan: pro, order limit 500
Zara orders 120: allowed
Zara orders 900: denied: over the pro plan's order limit of 500
Sam orders 120: denied: needs the customer role
Zara's old token orders 120: denied: the token has no plan

mvn -q compile exec:java
Zara's token: eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiJ1c2VyLTQyIiwiYXVkIjpbImh0dHBzOi8vb3JkZXJzLmV4YW1wbGUuY29tIl0sImlhdCI6MTc5NjI4NDQyMSwiZXhwIjoxNzk2Mjg1MzIxLCJuYW1lIjoiWmFyYSIsInJvbGVzIjpbImN1c3RvbWVyIiwiYmV0YS10ZXN0ZXIiXSwiaHR0cHM6Ly9vcmRlcnMuZXhhbXBsZS5jb20vcGxhbiI6eyJuYW1lIjoicHJvIiwib3JkZXJfbGltaXQiOjUwMH19.r5gdPC4IyDRQZLRLXY6QN3VoLMNg6VFzU93uSGGQM30
Custom claims in Zara's token:
name: Zara
roles: [customer, beta-tester]
plan: pro, order limit 500
Zara orders 120: allowed
Zara orders 900: denied: over the pro plan's order limit of 500
Sam orders 120: denied: needs the customer role
Zara's old token orders 120: denied: the token has no plan

go run .
Zara's token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiWmFyYSIsInJvbGVzIjpbImN1c3RvbWVyIiwiYmV0YS10ZXN0ZXIiXSwiaHR0cHM6Ly9vcmRlcnMuZXhhbXBsZS5jb20vcGxhbiI6eyJuYW1lIjoicHJvIiwib3JkZXJfbGltaXQiOjUwMH0sImlzcyI6Imh0dHBzOi8vYXV0aC5leGFtcGxlLmNvbSIsInN1YiI6InVzZXItNDIiLCJhdWQiOlsiaHR0cHM6Ly9vcmRlcnMuZXhhbXBsZS5jb20iXSwiZXhwIjoxNzk2Mjg1MzU4LCJpYXQiOjE3OTYyODQ0NTh9.ErIaWZkBQtAz514wywZUzvuTCJFnRDLz2aTghGgn5o4
Custom claims in Zara's token:
name: Zara
roles: customer, beta-tester
plan: pro, order limit 500
Zara orders 120: allowed
Zara orders 900: denied: over the pro plan's order limit of 500
Sam orders 120: denied: needs the customer role
Zara's old token orders 120: denied: the token has no plan

php main.php
Zara's token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiJ1c2VyLTQyIiwiYXVkIjoiaHR0cHM6Ly9vcmRlcnMuZXhhbXBsZS5jb20iLCJpYXQiOjE3OTYyODQ0ODAsImV4cCI6MTc5NjI4NTM4MCwibmFtZSI6IlphcmEiLCJyb2xlcyI6WyJjdXN0b21lciIsImJldGEtdGVzdGVyIl0sImh0dHBzOi8vb3JkZXJzLmV4YW1wbGUuY29tL3BsYW4iOnsibmFtZSI6InBybyIsIm9yZGVyX2xpbWl0Ijo1MDB9fQ.syMrWo-qDVt5zzdmCbGdXa_X4NWa8uT2-RMJ4X4K6Js
Custom claims in Zara's token:
name: Zara
roles: customer, beta-tester
plan: pro, order limit 500
Zara orders 120: allowed
Zara orders 900: denied: over the pro plan's order limit of 500
Sam orders 120: denied: needs the customer role
Zara's old token orders 120: denied: the token has no plan

bundle exec ruby main.rb
Zara's token: eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiJ1c2VyLTQyIiwiYXVkIjoiaHR0cHM6Ly9vcmRlcnMuZXhhbXBsZS5jb20iLCJpYXQiOjE3OTYyODQ1MDAsImV4cCI6MTc5NjI4NTQwMCwibmFtZSI6IlphcmEiLCJyb2xlcyI6WyJjdXN0b21lciIsImJldGEtdGVzdGVyIl0sImh0dHBzOi8vb3JkZXJzLmV4YW1wbGUuY29tL3BsYW4iOnsibmFtZSI6InBybyIsIm9yZGVyX2xpbWl0Ijo1MDB9fQ.L6PK5Tgg7q4OWiLp7Cuh12yeA8c2Xti2kvvVpLjeVLA
Custom claims in Zara's token:
name: Zara
roles: customer, beta-tester
plan: pro, order limit 500
Zara orders 120: allowed
Zara orders 900: denied: over the pro plan's order limit of 500
Sam orders 120: denied: needs the customer role
Zara's old token orders 120: denied: the token has no plan

cargo run -q
Zara's token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiJ1c2VyLTQyIiwiYXVkIjoiaHR0cHM6Ly9vcmRlcnMuZXhhbXBsZS5jb20iLCJpYXQiOjE3OTYyODQ1NDgsImV4cCI6MTc5NjI4NTQ0OCwibmFtZSI6IlphcmEiLCJyb2xlcyI6WyJjdXN0b21lciIsImJldGEtdGVzdGVyIl0sImh0dHBzOi8vb3JkZXJzLmV4YW1wbGUuY29tL3BsYW4iOnsibmFtZSI6InBybyIsIm9yZGVyX2xpbWl0Ijo1MDB9fQ.H2ONjS_h3cjEolYsQZLB1ZioQYOTF-xrFWkFnbE3_Ek
Custom claims in Zara's token:
name: Zara
roles: customer, beta-tester
plan: pro, order limit 500
Zara orders 120: allowed
Zara orders 900: denied: over the pro plan's order limit of 500
Sam orders 120: denied: needs the customer role
Zara's old token orders 120: denied: the token has no plan

Your token will differ, because the program makes a new one on every run. The rest of the output should match.
The Complete File
- Node.js
- Python
- C#
- Java
- Go
- PHP
- Ruby
- Rust
import { SignJWT, jwtVerify, errors } from 'jose';
const ISSUER = 'https://auth.example.com';
const ORDERS_API = 'https://orders.example.com';
// A custom claim name on the orders API's own domain, so nobody else's claim can have it.
const PLAN_CLAIM = 'https://orders.example.com/plan';
// The sign-in service's job: the registered claims plus the custom claims the orders API needs.
async function createToken(key, userId, name, roles, plan) {
const claims = {
name, // a string
roles, // an array of strings
};
if (plan) {
claims[PLAN_CLAIM] = plan; // an object: the plan's name and its order limit
}
const now = Math.floor(Date.now() / 1000);
return new SignJWT(claims)
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.setIssuer(ISSUER)
.setSubject(userId)
.setAudience(ORDERS_API)
.setIssuedAt(now)
.setExpirationTime(now + 15 * 60)
.sign(key);
}
// The orders API's check: the signature and the times, then the issuer and audience.
async function verifyForOrders(key, token) {
const { payload } = await jwtVerify(token, key, {
algorithms: ['HS256'],
issuer: ISSUER,
audience: ORDERS_API,
});
return payload;
}
// Print the custom claims of a verified token.
function showClaims(claims) {
const plan = claims[PLAN_CLAIM];
console.log(` name: ${claims.name}`);
console.log(` roles: ${claims.roles.join(', ')}`);
console.log(` plan: ${plan.name}, order limit ${plan.order_limit}`);
}
// The orders API's rule: a customer may order up to their plan's limit.
// A valid signature proves who wrote the claims, not that each one is there
// with the type the rule expects, so the rule checks that first.
function checkOrder(claims, amount) {
const roles = claims.roles;
if (!Array.isArray(roles) || !roles.includes('customer')) {
return 'denied: needs the customer role';
}
const plan = claims[PLAN_CLAIM];
if (typeof plan !== 'object' || plan === null || !Number.isInteger(plan.order_limit)) {
return 'denied: the token has no plan';
}
if (amount > plan.order_limit) {
return `denied: over the ${plan.name} plan's order limit of ${plan.order_limit}`;
}
return 'allowed';
}
// Show what the orders API makes of one order.
async function report(key, label, token, amount) {
try {
const claims = await verifyForOrders(key, token);
console.log(`${label}: ${checkOrder(claims, amount)}`);
} catch (err) {
if (!(err instanceof errors.JOSEError)) throw err;
console.log(`${label}: rejected: ${err.message}`);
}
}
// The key every service shares: 32 random bytes, kept as base64 text in JWT_SECRET.
const secret = process.env.JWT_SECRET;
if (!secret) {
console.error('Set the JWT_SECRET environment variable first.');
process.exit(1);
}
const key = Uint8Array.fromBase64(secret);
const zara = await createToken(key, 'user-42', 'Zara', ['customer', 'beta-tester'], {
name: 'pro',
order_limit: 500,
});
const sam = await createToken(key, 'user-7', 'Sam', ['support'], null);
// A token from the sign-in service's previous version, which didn't add plans yet.
const old = await createToken(key, 'user-42', 'Zara', ['customer', 'beta-tester'], null);
console.log(`Zara's token: ${zara}`);
console.log("Custom claims in Zara's token:");
showClaims(await verifyForOrders(key, zara));
await report(key, 'Zara orders 120', zara, 120);
await report(key, 'Zara orders 900', zara, 900);
await report(key, 'Sam orders 120', sam, 120);
await report(key, "Zara's old token orders 120", old, 120);

import base64
import os
import sys
from datetime import datetime, timedelta, timezone
import jwt
ISSUER = "https://auth.example.com"
ORDERS_API = "https://orders.example.com"
# A custom claim name on the orders API's own domain, so nobody else's claim can have it.
PLAN_CLAIM = "https://orders.example.com/plan"
def create_token(key: bytes, user_id: str, name: str, roles: list[str], plan: dict | None) -> str:
"""The sign-in service's job: the registered claims plus the custom claims the orders API needs."""
now = datetime.now(tz=timezone.utc)
payload = {
"iss": ISSUER,
"sub": user_id,
"aud": ORDERS_API,
"iat": now,
"exp": now + timedelta(minutes=15),
"name": name, # a string
"roles": roles, # a list of strings
}
if plan is not None:
payload[PLAN_CLAIM] = plan # a dictionary: the plan's name and its order limit
return jwt.encode(payload, key, algorithm="HS256")
def verify_for_orders(key: bytes, token: str) -> dict:
"""The orders API's check: the signature and the times, then the issuer and audience."""
return jwt.decode(token, key, algorithms=["HS256"], issuer=ISSUER, audience=ORDERS_API)
def show_claims(claims: dict) -> None:
"""Print the custom claims of a verified token."""
plan = claims[PLAN_CLAIM]
print(f" name: {claims['name']}")
print(f" roles: {', '.join(claims['roles'])}")
print(f" plan: {plan['name']}, order limit {plan['order_limit']}")
def check_order(claims: dict, amount: int) -> str:
"""The orders API's rule: a customer may order up to their plan's limit.
A valid signature proves who wrote the claims, not that each one is there
with the type the rule expects, so the rule checks that first.
"""
roles = claims.get("roles")
if not isinstance(roles, list) or "customer" not in roles:
return "denied: needs the customer role"
plan = claims.get(PLAN_CLAIM)
if not isinstance(plan, dict) or not isinstance(plan.get("order_limit"), int):
return "denied: the token has no plan"
if amount > plan["order_limit"]:
return f"denied: over the {plan['name']} plan's order limit of {plan['order_limit']}"
return "allowed"
def report(key: bytes, label: str, token: str, amount: int) -> None:
"""Show what the orders API makes of one order."""
try:
claims = verify_for_orders(key, token)
print(f"{label}: {check_order(claims, amount)}")
except jwt.InvalidTokenError as err:
print(f"{label}: rejected: {err}")
def main() -> None:
# The key every service shares: 32 random bytes, kept as base64 text in JWT_SECRET.
secret = os.environ.get("JWT_SECRET")
if not secret:
sys.exit("Set the JWT_SECRET environment variable first.")
key = base64.b64decode(secret, validate=True)
zara = create_token(key, "user-42", "Zara", ["customer", "beta-tester"], {"name": "pro", "order_limit": 500})
sam = create_token(key, "user-7", "Sam", ["support"], None)
# A token from the sign-in service's previous version, which didn't add plans yet.
old = create_token(key, "user-42", "Zara", ["customer", "beta-tester"], None)
print(f"Zara's token: {zara}")
print("Custom claims in Zara's token:")
show_claims(verify_for_orders(key, zara))
report(key, "Zara orders 120", zara, 120)
report(key, "Zara orders 900", zara, 900)
report(key, "Sam orders 120", sam, 120)
report(key, "Zara's old token orders 120", old, 120)
if __name__ == "__main__":
main()

using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
const string Issuer = "https://auth.example.com";
const string OrdersApi = "https://orders.example.com";
// A custom claim name on the orders API's own domain, so nobody else's claim can have it.
const string PlanClaim = "https://orders.example.com/plan";
// The key every service shares: 32 random bytes, kept as base64 text in JWT_SECRET.
var secret = Environment.GetEnvironmentVariable("JWT_SECRET");
if (string.IsNullOrEmpty(secret))
{
Console.Error.WriteLine("Set the JWT_SECRET environment variable first.");
return 1;
}
var key = Convert.FromBase64String(secret);
var zara = CreateToken(key, "user-42", "Zara", ["customer", "beta-tester"],
new Dictionary<string, object> { ["name"] = "pro", ["order_limit"] = 500 });
var sam = CreateToken(key, "user-7", "Sam", ["support"], null);
// A token from the sign-in service's previous version, which didn't add plans yet.
var old = CreateToken(key, "user-42", "Zara", ["customer", "beta-tester"], null);
Console.WriteLine($"Zara's token: {zara}");
Console.WriteLine("Custom claims in Zara's token:");
ShowClaims(await VerifyForOrdersAsync(key, zara));
await ReportAsync(key, "Zara orders 120", zara, 120);
await ReportAsync(key, "Zara orders 900", zara, 900);
await ReportAsync(key, "Sam orders 120", sam, 120);
await ReportAsync(key, "Zara's old token orders 120", old, 120);
return 0;
// The sign-in service's job: the registered claims plus the custom claims the orders API needs.
static string CreateToken(byte[] key, string userId, string name, string[] roles, Dictionary<string, object>? plan)
{
var claims = new Dictionary<string, object>
{
["sub"] = userId,
["name"] = name, // a string
["roles"] = roles, // an array of strings
};
if (plan is not null)
{
claims[PlanClaim] = plan; // an object: the plan's name and its order limit
}
var now = DateTime.UtcNow;
var descriptor = new SecurityTokenDescriptor
{
Issuer = Issuer,
Audience = OrdersApi,
IssuedAt = now,
Expires = now.AddMinutes(15),
Claims = claims,
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256),
};
return new JsonWebTokenHandler().CreateToken(descriptor);
}
// The orders API's check: the signature and the times, then the issuer and audience.
static async Task<JsonWebToken> VerifyForOrdersAsync(byte[] key, string token)
{
var parameters = new TokenValidationParameters
{
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidAlgorithms = [SecurityAlgorithms.HmacSha256],
ValidIssuer = Issuer,
ValidAudience = OrdersApi,
};
var result = await new JsonWebTokenHandler().ValidateTokenAsync(token, parameters);
if (!result.IsValid)
{
throw result.Exception;
}
return (JsonWebToken)result.SecurityToken;
}
// Print the custom claims of a verified token.
static void ShowClaims(JsonWebToken token)
{
var plan = token.GetPayloadValue<Dictionary<string, object>>(PlanClaim);
Console.WriteLine($" name: {token.GetPayloadValue<string>("name")}");
Console.WriteLine($" roles: {string.Join(", ", token.GetPayloadValue<string[]>("roles"))}");
Console.WriteLine($" plan: {plan["name"]}, order limit {plan["order_limit"]}");
}
// The orders API's rule: a customer may order up to their plan's limit.
// A valid signature proves who wrote the claims, not that each one is there
// with the type the rule expects, so the rule checks that first.
static string CheckOrder(JsonWebToken token, int amount)
{
if (!token.TryGetPayloadValue<string[]>("roles", out var roles) || !roles.Contains("customer"))
{
return "denied: needs the customer role";
}
if (!token.TryGetPayloadValue<Dictionary<string, object>>(PlanClaim, out var plan)
|| plan.GetValueOrDefault("order_limit") is not int orderLimit)
{
return "denied: the token has no plan";
}
if (amount > orderLimit)
{
return $"denied: over the {plan["name"]} plan's order limit of {orderLimit}";
}
return "allowed";
}
// Show what the orders API makes of one order.
static async Task ReportAsync(byte[] key, string label, string token, int amount)
{
try
{
var verified = await VerifyForOrdersAsync(key, token);
Console.WriteLine($"{label}: {CheckOrder(verified, amount)}");
}
catch (SecurityTokenException ex)
{
// The exception's type names the check that failed; that's all this program shows.
Console.WriteLine($"{label}: rejected: {ex.GetType().Name}");
}
}

package com.example;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.crypto.SecretKey;
public class Main {
static final String ISSUER = "https://auth.example.com";
static final String ORDERS_API = "https://orders.example.com";
// A custom claim name on the orders API's own domain, so nobody else's claim can have it.
static final String PLAN_CLAIM = "https://orders.example.com/plan";
// The sign-in service's job: the registered claims plus the custom claims the orders API needs.
static String createToken(SecretKey key, String userId, String name, List<String> roles,
Map<String, Object> plan) {
Instant now = Instant.now();
return Jwts.builder()
.issuer(ISSUER)
.subject(userId)
.audience().add(ORDERS_API).and()
.issuedAt(Date.from(now))
.expiration(Date.from(now.plus(Duration.ofMinutes(15))))
.claim("name", name) // a string
.claim("roles", roles) // an array of strings
.claim(PLAN_CLAIM, plan) // an object: the plan's name and its order limit; null leaves it out
.signWith(key, Jwts.SIG.HS256)
.compact();
}
// The orders API's check: the signature and the times, then the issuer and audience.
static Claims verifyForOrders(SecretKey key, String token) {
return Jwts.parser()
.verifyWith(key)
.requireIssuer(ISSUER)
.requireAudience(ORDERS_API)
.build()
.parseSignedClaims(token)
.getPayload();
}
// Print the custom claims of a verified token.
static void showClaims(Claims claims) {
Map<?, ?> plan = claims.get(PLAN_CLAIM, Map.class);
System.out.println(" name: " + claims.get("name", String.class));
System.out.println(" roles: " + claims.get("roles", List.class));
System.out.println(" plan: " + plan.get("name") + ", order limit " + plan.get("order_limit"));
}
// The orders API's rule: a customer may order up to their plan's limit.
// A valid signature proves who wrote the claims, not that each one is there
// with the type the rule expects, so the rule checks that first.
static String checkOrder(Claims claims, int amount) {
if (!(claims.get("roles") instanceof List<?> roles) || !roles.contains("customer")) {
return "denied: needs the customer role";
}
if (!(claims.get(PLAN_CLAIM) instanceof Map<?, ?> plan)
|| !(plan.get("order_limit") instanceof Integer orderLimit)) {
return "denied: the token has no plan";
}
if (amount > orderLimit) {
return "denied: over the " + plan.get("name") + " plan's order limit of " + orderLimit;
}
return "allowed";
}
// Show what the orders API makes of one order.
static void report(SecretKey key, String label, String token, int amount) {
try {
Claims claims = verifyForOrders(key, token);
System.out.println(label + ": " + checkOrder(claims, amount));
} catch (JwtException e) {
System.out.println(label + ": rejected: " + e.getMessage());
}
}
public static void main(String[] args) {
// The key every service shares: 32 random bytes, kept as base64 text in JWT_SECRET.
String secret = System.getenv("JWT_SECRET");
if (secret == null || secret.isEmpty()) {
System.err.println("Set the JWT_SECRET environment variable first.");
System.exit(1);
}
SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));
String zara = createToken(key, "user-42", "Zara", List.of("customer", "beta-tester"),
Map.of("name", "pro", "order_limit", 500));
String sam = createToken(key, "user-7", "Sam", List.of("support"), null);
// A token from the sign-in service's previous version, which didn't add plans yet.
String old = createToken(key, "user-42", "Zara", List.of("customer", "beta-tester"), null);
System.out.println("Zara's token: " + zara);
System.out.println("Custom claims in Zara's token:");
showClaims(verifyForOrders(key, zara));
report(key, "Zara orders 120", zara, 120);
report(key, "Zara orders 900", zara, 900);
report(key, "Sam orders 120", sam, 120);
report(key, "Zara's old token orders 120", old, 120);
}
}

package main
import (
"encoding/base64"
"fmt"
"os"
"slices"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
)
const (
issuer = "https://auth.example.com"
ordersAPI = "https://orders.example.com"
)
// Plan is the value of the plan claim: a JSON object.
type Plan struct {
Name string `json:"name"`
OrderLimit int `json:"order_limit"`
}
// OrderClaims is the token's payload: the custom claims plus the registered ones.
// The plan claim's name is on the orders API's own domain, so nobody else's claim can have it.
type OrderClaims struct {
Name string `json:"name"` // a string
Roles []string `json:"roles"` // an array of strings
Plan *Plan `json:"https://orders.example.com/plan,omitempty"` // an object, left out when nil
jwt.RegisteredClaims
}
// createToken does the sign-in service's job: the registered claims plus
// the custom claims the orders API needs.
func createToken(key []byte, userID, name string, roles []string, plan *Plan) (string, error) {
now := time.Now()
claims := OrderClaims{
Name: name,
Roles: roles,
Plan: plan,
RegisteredClaims: jwt.RegisteredClaims{
Issuer: issuer,
Subject: userID,
Audience: jwt.ClaimStrings{ordersAPI},
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(15 * time.Minute)),
},
}
return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(key)
}
// verifyForOrders is the orders API's check: the signature and the times,
// then the issuer and audience.
func verifyForOrders(key []byte, token string) (*OrderClaims, error) {
claims := &OrderClaims{}
_, err := jwt.ParseWithClaims(token, claims, func(*jwt.Token) (any, error) {
return key, nil
},
jwt.WithValidMethods([]string{"HS256"}),
jwt.WithIssuer(issuer),
jwt.WithAudience(ordersAPI),
)
if err != nil {
return nil, err
}
return claims, nil
}
// showClaims prints the custom claims of a verified token.
func showClaims(claims *OrderClaims) {
fmt.Printf(" name: %s\n", claims.Name)
fmt.Printf(" roles: %s\n", strings.Join(claims.Roles, ", "))
fmt.Printf(" plan: %s, order limit %d\n", claims.Plan.Name, claims.Plan.OrderLimit)
}
// checkOrder is the orders API's rule: a customer may order up to their plan's limit.
// ParseWithClaims already rejected a token whose claims don't fit the struct's types,
// but a claim the token leaves out is nil or empty, so the rule checks for that.
func checkOrder(claims *OrderClaims, amount int) string {
if !slices.Contains(claims.Roles, "customer") {
return "denied: needs the customer role"
}
if claims.Plan == nil {
return "denied: the token has no plan"
}
if amount > claims.Plan.OrderLimit {
return fmt.Sprintf("denied: over the %s plan's order limit of %d", claims.Plan.Name, claims.Plan.OrderLimit)
}
return "allowed"
}
// report shows what the orders API makes of one order.
func report(key []byte, label, token string, amount int) {
claims, err := verifyForOrders(key, token)
if err != nil {
fmt.Printf("%s: rejected: %v\n", label, err)
return
}
fmt.Printf("%s: %s\n", label, checkOrder(claims, amount))
}
// fail prints a message to standard error and stops the program.
func fail(a ...any) {
fmt.Fprintln(os.Stderr, a...)
os.Exit(1)
}
func main() {
// The key every service shares: 32 random bytes, kept as base64 text in JWT_SECRET.
secret := os.Getenv("JWT_SECRET")
if secret == "" {
fail("Set the JWT_SECRET environment variable first.")
}
key, err := base64.StdEncoding.DecodeString(secret)
if err != nil {
fail("JWT_SECRET is not valid base64:", err)
}
zara, err := createToken(key, "user-42", "Zara", []string{"customer", "beta-tester"},
&Plan{Name: "pro", OrderLimit: 500})
if err != nil {
fail("Could not create the token:", err)
}
sam, err := createToken(key, "user-7", "Sam", []string{"support"}, nil)
if err != nil {
fail("Could not create the token:", err)
}
// A token from the sign-in service's previous version, which didn't add plans yet.
old, err := createToken(key, "user-42", "Zara", []string{"customer", "beta-tester"}, nil)
if err != nil {
fail("Could not create the token:", err)
}
fmt.Printf("Zara's token: %s\n", zara)
fmt.Println("Custom claims in Zara's token:")
claims, err := verifyForOrders(key, zara)
if err != nil {
fail("Zara's token was rejected:", err)
}
showClaims(claims)
report(key, "Zara orders 120", zara, 120)
report(key, "Zara orders 900", zara, 900)
report(key, "Sam orders 120", sam, 120)
report(key, "Zara's old token orders 120", old, 120)
}

<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
const ISSUER = 'https://auth.example.com';
const ORDERS_API = 'https://orders.example.com';
// A custom claim name on the orders API's own domain, so nobody else's claim can have it.
const PLAN_CLAIM = 'https://orders.example.com/plan';
// The sign-in service's job: the registered claims plus the custom claims the orders API needs.
function createToken(string $key, string $userId, string $name, array $roles, ?array $plan): string
{
$now = time();
$payload = [
'iss' => ISSUER,
'sub' => $userId,
'aud' => ORDERS_API,
'iat' => $now,
'exp' => $now + 15 * 60,
'name' => $name, // a string
'roles' => $roles, // an array of strings
];
if ($plan !== null) {
$payload[PLAN_CLAIM] = $plan; // an object: the plan's name and its order limit
}
return JWT::encode($payload, $key, 'HS256');
}
// The orders API's check: the signature and the times, then the issuer and audience.
// php-jwt checks the signature, exp, nbf and iat itself, but not iss or aud,
// so this function checks those two.
function verifyForOrders(string $key, string $token): stdClass
{
$claims = JWT::decode($token, new Key($key, 'HS256'));
if (($claims->iss ?? null) !== ISSUER) {
throw new UnexpectedValueException('Invalid issuer');
}
// aud can be one string or an array of strings, so turn it into an array first.
$audiences = (array) ($claims->aud ?? []);
if (!in_array(ORDERS_API, $audiences, true)) {
throw new UnexpectedValueException('Invalid audience');
}
return $claims;
}
// Print the custom claims of a verified token.
function showClaims(stdClass $claims): void
{
$plan = $claims->{PLAN_CLAIM};
echo " name: {$claims->name}\n";
echo ' roles: ' . implode(', ', $claims->roles) . "\n";
echo " plan: {$plan->name}, order limit {$plan->order_limit}\n";
}
// The orders API's rule: a customer may order up to their plan's limit.
// A valid signature proves who wrote the claims, not that each one is there
// with the type the rule expects, so the rule checks that first.
function checkOrder(stdClass $claims, int $amount): string
{
$roles = $claims->roles ?? null;
if (!is_array($roles) || !in_array('customer', $roles, true)) {
return 'denied: needs the customer role';
}
$plan = $claims->{PLAN_CLAIM} ?? null;
if (!($plan instanceof stdClass) || !is_int($plan->order_limit ?? null)) {
return 'denied: the token has no plan';
}
if ($amount > $plan->order_limit) {
return "denied: over the {$plan->name} plan's order limit of {$plan->order_limit}";
}
return 'allowed';
}
// Show what the orders API makes of one order.
function report(string $key, string $label, string $token, int $amount): void
{
try {
$claims = verifyForOrders($key, $token);
echo "{$label}: " . checkOrder($claims, $amount) . "\n";
} catch (UnexpectedValueException $e) {
echo "{$label}: rejected: {$e->getMessage()}\n";
}
}
// The key every service shares: 32 random bytes, kept as base64 text in JWT_SECRET.
$secret = getenv('JWT_SECRET');
if ($secret === false || $secret === '') {
fwrite(STDERR, "Set the JWT_SECRET environment variable first.\n");
exit(1);
}
$key = base64_decode($secret, true);
if ($key === false) {
fwrite(STDERR, "JWT_SECRET is not valid base64.\n");
exit(1);
}
$zara = createToken($key, 'user-42', 'Zara', ['customer', 'beta-tester'], ['name' => 'pro', 'order_limit' => 500]);
$sam = createToken($key, 'user-7', 'Sam', ['support'], null);
// A token from the sign-in service's previous version, which didn't add plans yet.
$old = createToken($key, 'user-42', 'Zara', ['customer', 'beta-tester'], null);
echo "Zara's token: {$zara}\n";
echo "Custom claims in Zara's token:\n";
showClaims(verifyForOrders($key, $zara));
report($key, 'Zara orders 120', $zara, 120);
report($key, 'Zara orders 900', $zara, 900);
report($key, 'Sam orders 120', $sam, 120);
report($key, "Zara's old token orders 120", $old, 120);

require 'jwt'
ISSUER = 'https://auth.example.com'
ORDERS_API = 'https://orders.example.com'
# A custom claim name on the orders API's own domain, so nobody else's claim can have it.
PLAN_CLAIM = 'https://orders.example.com/plan'
# The sign-in service's job: the registered claims plus the custom claims the orders API needs.
def create_token(key, user_id, name, roles, plan)
now = Time.now.to_i
payload = {
'iss' => ISSUER,
'sub' => user_id,
'aud' => ORDERS_API,
'iat' => now,
'exp' => now + (15 * 60),
'name' => name, # a string
'roles' => roles # an array of strings
}
payload[PLAN_CLAIM] = plan if plan # a hash: the plan's name and its order limit
JWT.encode(payload, key, 'HS256')
end
# The orders API's check: the signature and the times, then the issuer and audience.
def verify_for_orders(key, token)
claims, _header = JWT.decode(token, key, true,
algorithm: 'HS256',
iss: ISSUER, verify_iss: true,
aud: ORDERS_API, verify_aud: true)
claims
end
# Print the custom claims of a verified token.
def show_claims(claims)
plan = claims[PLAN_CLAIM]
puts " name: #{claims['name']}"
puts " roles: #{claims['roles'].join(', ')}"
puts " plan: #{plan['name']}, order limit #{plan['order_limit']}"
end
# The orders API's rule: a customer may order up to their plan's limit.
# A valid signature proves who wrote the claims, not that each one is there
# with the type the rule expects, so the rule checks that first.
def check_order(claims, amount)
roles = claims['roles']
return 'denied: needs the customer role' unless roles.is_a?(Array) && roles.include?('customer')
plan = claims[PLAN_CLAIM]
return 'denied: the token has no plan' unless plan.is_a?(Hash) && plan['order_limit'].is_a?(Integer)
if amount > plan['order_limit']
return "denied: over the #{plan['name']} plan's order limit of #{plan['order_limit']}"
end
'allowed'
end
# Show what the orders API makes of one order.
def report(key, label, token, amount)
claims = verify_for_orders(key, token)
puts "#{label}: #{check_order(claims, amount)}"
rescue JWT::DecodeError => e
puts "#{label}: rejected: #{e.message}"
end
# The key every service shares: 32 random bytes, kept as base64 text in JWT_SECRET.
secret = ENV.fetch('JWT_SECRET', '')
abort 'Set the JWT_SECRET environment variable first.' if secret.empty?
key = secret.unpack1('m0')
zara = create_token(key, 'user-42', 'Zara', %w[customer beta-tester], { 'name' => 'pro', 'order_limit' => 500 })
sam = create_token(key, 'user-7', 'Sam', %w[support], nil)
# A token from the sign-in service's previous version, which didn't add plans yet.
old = create_token(key, 'user-42', 'Zara', %w[customer beta-tester], nil)
puts "Zara's token: #{zara}"
puts "Custom claims in Zara's token:"
show_claims(verify_for_orders(key, zara))
report(key, 'Zara orders 120', zara, 120)
report(key, 'Zara orders 900', zara, 900)
report(key, 'Sam orders 120', sam, 120)
report(key, "Zara's old token orders 120", old, 120)

use std::time::{SystemTime, UNIX_EPOCH};
use jsonwebtoken::errors::Error;
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
use serde::{Deserialize, Serialize};
const ISSUER: &str = "https://auth.example.com";
const ORDERS_API: &str = "https://orders.example.com";
/// The value of the plan claim: a JSON object.
#[derive(Debug, Serialize, Deserialize)]
struct Plan {
name: String,
order_limit: u32,
}
/// The token's payload: the registered claims plus the custom ones.
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
iss: String,
sub: String,
aud: String,
iat: u64,
exp: u64,
name: String, // a string
roles: Vec<String>, // an array of strings
// An object, named with a URL on the orders API's own domain so nobody else's
// claim can have it, and left out of the token when there's no plan.
#[serde(
rename = "https://orders.example.com/plan",
skip_serializing_if = "Option::is_none"
)]
plan: Option<Plan>,
}
/// The sign-in service's job: the registered claims plus the custom claims the orders API needs.
fn create_token(
key: &EncodingKey,
user_id: &str,
name: &str,
roles: &[&str],
plan: Option<Plan>,
) -> Result<String, Error> {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("the clock is set before 1970")
.as_secs();
let claims = Claims {
iss: ISSUER.to_owned(),
sub: user_id.to_owned(),
aud: ORDERS_API.to_owned(),
iat: now,
exp: now + 15 * 60,
name: name.to_owned(),
roles: roles.iter().map(|role| role.to_string()).collect(),
plan,
};
encode(&Header::new(Algorithm::HS256), &claims, key)
}
/// The orders API's check: the signature and the times, then the issuer and audience.
fn verify_for_orders(key: &DecodingKey, token: &str) -> Result<Claims, Error> {
let mut validation = Validation::new(Algorithm::HS256);
validation.set_issuer(&[ISSUER]);
validation.set_audience(&[ORDERS_API]);
// Reject tokens that leave out exp, iss or aud.
validation.set_required_spec_claims(&["exp", "iss", "aud"]);
let data = decode::<Claims>(token, key, &validation)?;
Ok(data.claims)
}
/// Print the custom claims of a verified token.
fn show_claims(claims: &Claims) {
println!(" name: {}", claims.name);
println!(" roles: {}", claims.roles.join(", "));
if let Some(plan) = &claims.plan {
println!(" plan: {}, order limit {}", plan.name, plan.order_limit);
}
}
/// The orders API's rule: a customer may order up to their plan's limit.
/// decode already rejected a token whose claims don't fit the struct's types,
/// and a plan the token leaves out is None, so the rule checks for that.
fn check_order(claims: &Claims, amount: u32) -> String {
if !claims.roles.iter().any(|role| role == "customer") {
return "denied: needs the customer role".to_owned();
}
let Some(plan) = &claims.plan else {
return "denied: the token has no plan".to_owned();
};
if amount > plan.order_limit {
return format!(
"denied: over the {} plan's order limit of {}",
plan.name, plan.order_limit
);
}
"allowed".to_owned()
}
/// Show what the orders API makes of one order.
fn report(key: &DecodingKey, label: &str, token: &str, amount: u32) {
match verify_for_orders(key, token) {
Ok(claims) => println!("{label}: {}", check_order(&claims, amount)),
Err(err) => println!("{label}: rejected: {err}"),
}
}
fn main() -> Result<(), Error> {
// The key every service shares: 32 random bytes, kept as base64 text in JWT_SECRET.
let secret = std::env::var("JWT_SECRET").unwrap_or_default();
if secret.is_empty() {
eprintln!("Set the JWT_SECRET environment variable first.");
std::process::exit(1);
}
let encoding_key = EncodingKey::from_base64_secret(&secret)?;
let decoding_key = DecodingKey::from_base64_secret(&secret)?;
let pro = Plan {
name: "pro".to_owned(),
order_limit: 500,
};
let zara = create_token(
&encoding_key,
"user-42",
"Zara",
&["customer", "beta-tester"],
Some(pro),
)?;
let sam = create_token(&encoding_key, "user-7", "Sam", &["support"], None)?;
// A token from the sign-in service's previous version, which didn't add plans yet.
let old = create_token(
&encoding_key,
"user-42",
"Zara",
&["customer", "beta-tester"],
None,
)?;
println!("Zara's token: {zara}");
println!("Custom claims in Zara's token:");
show_claims(&verify_for_orders(&decoding_key, &zara)?);
report(&decoding_key, "Zara orders 120", &zara, 120);
report(&decoding_key, "Zara orders 900", &zara, 900);
report(&decoding_key, "Sam orders 120", &sam, 120);
report(&decoding_key, "Zara's old token orders 120", &old, 120);
Ok(())
}

What the Run Shows
- Zara's first order passed every check. Her token is valid, she has the
customerrole, and 120 is within theproplan's limit of 500. The orders API decided without looking Zara up anywhere: everything it needed was in the token. - Her second order was turned down by the plan, not by the token. Same token, same claims, but 900 is over the limit.
- Sam's token was valid too, and still denied. A valid signature says the claims are genuine. It doesn't say they allow the order: Sam works in support and isn't a customer.
- Zara's old token had no plan claim, and the orders API denied the order instead of crashing or letting it through. Tokens outlive the code that made them: a token issued just before a new sign-in service goes live still reaches the API, so the API has to handle a claim that isn't there.
- Java printed the roles in brackets, because
claims.get("roles", List.class)returns a JavaList. Every other program joined them with a comma.
How Each Library Reads Custom Claims
Each library turns the payload's JSON into its own types, and they don't agree on how. This table comes from reading extra tokens made for the purpose, whose custom claims included every JSON type:
| Language | Library | Read a claim with | A JSON array becomes | A JSON object becomes | A claim the token leaves out |
|---|---|---|---|---|---|
| Node.js | jose | payload.roles, or payload[name] for any name | Array | a plain object | undefined |
| Python | PyJWT | claims.get("roles") or claims["roles"] | list | dict | None from get, a KeyError from [] |
| C# | JsonWebTokenHandler | TryGetPayloadValue<T> or GetPayloadValue<T> | the type you ask for, such as string[] | the type you ask for, such as Dictionary<string, object> | false from TryGetPayloadValue; GetPayloadValue throws IDX14304 |
| Java | jjwt | claims.get("roles"), or claims.get("roles", List.class) | ArrayList | LinkedHashMap | null |
| Go | golang-jwt | the fields of your claims struct | the field's type, such as []string | the field's type, such as *Plan | the field's zero value: nil for a slice or a pointer |
| PHP | php-jwt | $claims->roles, or $claims->{$name} for any name | array | stdClass | null, with an Undefined property warning unless you use ?? |
| Ruby | jwt | claims['roles'] | Array | Hash | nil |
| Rust | jsonwebtoken | the fields of your claims struct | the field's type, such as Vec<String> | the field's type, such as Plan | None for an Option field; any other field rejects the whole token |
Two more differences showed up in the same tokens. golang-jwt also offers jwt.MapClaims, a map you can read claims from without a struct, and it reads every number as a float64, even 500. And jjwt drops a claim whose value is null, so claims.containsKey says the token doesn't have it.
When a Claim Has the Wrong Type
To see what each library does with a claim of the wrong type, the orders API was handed two more tokens with valid signatures: one whose roles is the string "customer" instead of an array, and one whose order limit is the string "500" instead of a number. Here is what the program from this tutorial decided:
| Language | Library | roles is the string "customer" | order_limit is the string "500" |
|---|---|---|---|
| Node.js | jose | Denied: not an array | Denied: not a whole number |
| Python | PyJWT | Denied: not a list | Denied: not an int |
| C# | JsonWebTokenHandler | Allowed: TryGetPayloadValue<string[]> reads one string as an array of one | Denied: a string, not an int |
| Java | jjwt | Denied: not a List | Denied: not an Integer |
| Go | golang-jwt | Rejected: cannot unmarshal string into Go struct field Claims.roles of type []string | Rejected: cannot unmarshal string into Go struct field Claims.https:~1~1orders.example.com~1plan.order_limit of type int |
| PHP | php-jwt | Denied: not an array | Denied: not an int |
| Ruby | jwt | Denied: not an Array | Denied: not an Integer |
| Rust | jsonwebtoken | Rejected: invalid type: string "customer", expected a sequence at line 1 column 151 | Rejected: invalid type: string "500", expected u32 at line 1 column 221 |
Go's message writes each / in the claim's name as ~1, and Rust's ends with the position in the payload's JSON just after the wrong value. Go and Rust reject the whole token before your code sees it, because the claims have to fit the struct you declared. The other six hand your code whatever the token holds, and the checks in Step 5 are what turn the order down. .NET is the one library that lets a single string count as a list. That's still safe for a role, because the role still has to match exactly: a roles of "not-a-customer" became an array holding not-a-customer, and the order was denied.
Without the type checks, three of the eight languages would have let a wrong value through. Given a token whose roles is the string "not-a-customer", roles.includes('customer') in JavaScript, 'customer' in roles in Python and roles.include?('customer') in Ruby are all true, because on a string each of them searches the text. PHP's in_array stops with a TypeError instead, and jjwt's claims.get("roles", List.class) throws a RequiredTypeException.
What You Can Do Now
- Tell registered, public and private claim names apart, and give a custom claim a name that can't collide.
- Add custom claims of any JSON type to a token, in any of the eight languages.
- Read them back after verifying the token, and check that each one is there with the type your code needs.
- Decide what belongs in a claim and what the API should look up instead.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Using a short private name such as plan or role across teams | Another service uses the same name for something else, and an API reads a value meant for another | Use a registered name with its registered meaning, or a URL on your own domain |
Giving a registered name a meaning of your own, such as scope as an array | Libraries and services that know the registered meaning misread it | Check the IANA registry first, and pick another name |
| Reading claims before verifying the token | Anyone can write any claim into a token they make themselves | Verify first, then read |
Checking for a role without checking that roles is an array | In JavaScript, Python and Ruby, the string "not-a-customer" passes a check for customer | Check the type first, as Step 5 does |
| Assuming every token has every claim | A token from an older sign-in service, like Zara's old token, crashes the code or skips the check | Treat a missing claim as a reason to deny |
| Putting private data or secrets in a claim | Anyone who holds the token can read them | Leave them out, and look them up on the server |
| Putting data that must be current in a claim | The token keeps the old value until it expires | Keep tokens short-lived, and look up what must be current |
Making authorization decisions from name or an email address | They're for display, and they can change or repeat | Decide from sub, roles and other claims meant for it |
| C#: a class or record of your own as a claim value | IdentityModel stops with IDX11025: Cannot serialize object of type | Use a Dictionary<string, object>, as Step 3 does |
Go: reading claims into jwt.MapClaims and expecting an int | Every number comes back as a float64 | Read them into a struct with typed fields, as this tutorial does |
| Java: an empty string, list or map as a custom claim's value | jjwt keeps it in the token, although its documentation says an empty value removes the claim | Add the claim only when it has a value |
PHP: NAN or INF as a claim value, such as the result of fdiv() dividing by zero | php-jwt stops with Unknown JSON error: 7, because JSON can't hold them | Check the number with is_finite() first |
Python: float("nan") or float("inf") as a claim value | PyJWT writes NaN or Infinity into the payload, which isn't JSON, and other languages' libraries reject the token | Send None for "no value" |
Rust: a field that isn't an Option for a claim that can be missing | The whole token is rejected with missing field `roles` | Make the field an Option |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Set the JWT_SECRET environment variable first. | Step 2 ran in another terminal, or not at all | Run Step 2 again in the terminal where you run the program |
C#: System.ArgumentException: IDX11025: Cannot serialize object of type: 'Plan' into property: 'https://orders.example.com/plan'. | A claim's value is an object of a class or record of your own | Use a dictionary instead |
C#: IDX14304: Claim with name '[PII of type 'System.String' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]' does not exist in the JsonClaimSet. | GetPayloadValue asked for a claim the token doesn't have | Use TryGetPayloadValue, as Step 5 does |
Go: token is malformed: could not JSON decode claim: json: cannot unmarshal string into Go struct field Claims.roles of type []string | A claim's JSON type doesn't match its field's type | Check what the sign-in service writes, and give the field the matching type |
Rust: JSON error: missing field `roles` at line 1 column 200 | The token doesn't have a claim whose field isn't an Option | Make the field an Option if the claim can be missing |
Rust: JSON error: invalid type: string "customer", expected a sequence at line 1 column 151 | A claim's JSON type doesn't match its field's type | Check what the sign-in service writes, and give the field the matching type |
PHP: Warning: Undefined property: stdClass::$missing, with the claim's name after the $ | The code reads a claim the token doesn't have | Add ?? null, as Step 5 does |
PHP: in_array(): Argument #2 ($haystack) must be of type array, string given | roles is a string, not an array | Check is_array first, as Step 5 does |
PHP: DomainException: Unknown JSON error: 7 from JWT::encode | A claim's value is NAN or INF, which JSON can't hold | Add the claim only when is_finite() says it's a finite number |
Python: KeyError with the claim's name | claims["..."] on a claim the token doesn't have | Use claims.get("...") |
Node.js: JWTInvalid: JWT Claims Set must be a top-level JSON object, with a [cause] that shows NaN | A Python service wrote float("nan") into a claim with PyJWT | Send None instead, and make PyJWT refuse NaN |
Java: io.jsonwebtoken.RequiredTypeException: Cannot convert existing claim value of type 'class java.lang.String' to desired type 'interface java.util.List'. JJWT only converts simple String, Date, Long, Integer, Short and Byte types automatically. …, and the message goes on | claims.get(name, List.class) on a claim that isn't a list | Check with instanceof, as Step 5 does |
Java: io.jsonwebtoken.io.SerializationException: Cannot serialize JWS Payload to JSON. Cause: Unable to serialize object of type io.jsonwebtoken.impl.DefaultClaims: Java 8 date/time type java.time.Instant not supported by default …, and the message goes on | A java.time value, such as an Instant, in a claim | Send the time as seconds since 1970 |
Frequently Asked Questions
What's the difference between public and private claims?
A public claim name is either registered in IANA's JSON Web Token Claims registry, such as roles, or contains a collision-resistant name, such as a URL on your own domain. A private claim name is any other name that the sign-in service and the API agree on, such as plan. RFC 7519 warns that private names "are subject to collision and should be used with caution".
Do custom claim names have to be URLs?
No. A registered name such as name or roles is fine when you use it with its registered meaning, and a private name is fine when one team controls every service that makes and reads the token. A URL on your own domain is the safe choice for everything else.
Are custom claims encrypted?
No. A signed JWT's payload is only base64url-encoded, so anyone who holds the token can read every claim. The signature only stops them from changing one. Keep private data out of claims, or encrypt the whole token, which JWE: Encrypted JWTs (coming soon) covers.
Can I put a user's permissions in a token?
Yes, and roles and permissions are the most common custom claims. Remember that they're fixed until the token expires: a user whose role is taken away keeps it until their token runs out. Keep such tokens short-lived.
Should a list of roles be an array or a space-separated string?
Use an array for roles, which RFC 7643 defines as a list. scope is the registered exception, a single string of names separated by spaces. Whichever shape your sign-in service writes, the API has to read the same one, which is why the orders API checks it.
How many custom claims can a token have?
The standard sets no limit, but every claim travels with every request, so keep them few and small. Sign-in services set their own limits: Firebase allows 1000 bytes of custom claims, and Auth0 allows 100 KB.
Conclusion
Custom claims carry what your API needs to make a decision: who the user is to your application and what they may do. Name them so they can't collide, with a registered name in its registered meaning or a URL on your own domain. Then treat every claim, even in a verified token, as a value to check before you use it. The run showed why: Sam's and Zara's old tokens were both signed correctly, and only the checks in Step 5 kept their orders out.
Next: Expiry, Not-Before and Clock Skew (coming soon). How each library checks exp and nbf, how much clock difference it allows, and what happens to a token without exp.
Additional Resources
- RFC 7519 sections 4.2 and 4.3, public and private claim names, and the JSON Web Token Claims registry at IANA, which lists every registered name.
- RFC 9068 section 2.2.3.1, on
roles,groupsandentitlementsin access tokens, and RFC 7643 section 4.1.2, where SCIM defines them. - SignJWT and JWTPayload, in the jose documentation.
- Usage Examples, in the PyJWT documentation.
- SecurityTokenDescriptor.Claims and JsonWebToken.TryGetPayloadValue, on Microsoft Learn.
- Custom Claims, in the jjwt README.
- The custom claims example, in the golang-jwt documentation.
- php-jwt, the PHP library, and ruby-jwt, the Ruby one.
- jsonwebtoken, and serde's field attributes, for
renameandskip_serializing_if. - How Microsoft Entra ID, Auth0, Firebase and Amazon Cognito use custom claims.