Registered Claims
Every token so far in this course carried a sub and an exp. Those are two of seven claim names the JWT standard sets aside for jobs nearly every application has: saying who made a token, who it's about, who it's for, when it counts and which token it is. This tutorial explains all seven, then builds a sign-in service that sets every one of them and an orders API that checks who made each token and who it's for, in eight languages. All three tokens it makes carry a valid signature, and the orders API still turns two of them away.
The Seven Registered Claims
A JWT's payload is a JSON object, and each of its members is a claim: a name and a value. You can make up names of your own, which Custom Claims (coming soon) covers. RFC 7519, the JWT standard, registers seven names for jobs nearly every token has, and every JWT library knows them:
| Claim | Name | What it says | Example value |
|---|---|---|---|
iss | Issuer | Who made the token | "https://auth.example.com" |
sub | Subject | Who or what the token is about | "user-42" |
aud | Audience | Who the token is for | "https://orders.example.com" |
exp | Expiration Time | When the token stops counting | 1796058773 |
nbf | Not Before | When the token starts counting | 1796057873 |
iat | Issued At | When the token was made | 1796057873 |
jti | JWT ID | This one token's own ID | "881a921a-e755-4e83-9a21-bd7e53ffeee4" |
Decoded, the payload of a token with all seven looks like this. It's the token the Node.js program in this tutorial printed:
{
"iss": "https://auth.example.com",
"sub": "user-42",
"aud": "https://orders.example.com",
"iat": 1796057873,
"nbf": 1796057873,
"exp": 1796058773,
"jti": "881a921a-e755-4e83-9a21-bd7e53ffeee4"
}
The names are only three letters long for a reason the standard gives itself: "All the names are short because a core goal of JWTs is for the representation to be compact." Every byte of a token travels with every request.
Every Registered Claim Is Optional
RFC 7519 doesn't make any of the seven mandatory. Section 4.1 says: "None of the claims defined below are intended to be mandatory to use or implement in all cases, but rather they provide a starting point for a set of useful, interoperable claims. Applications using JWTs should define which specific claims they use and when they are required or optional."
So the choice is yours: which claims your tokens carry, and which ones your API refuses to do without. Libraries don't make that choice the same way. Given the same token, the eight libraries in this tutorial disagreed about what to check and what to require, as How Each Library Checks iss and aud and Which Claims to Require show.
Two Kinds of Values
The seven claims hold two kinds of values, which section 2 of RFC 7519 defines:
- StringOrURI, for
iss,subandaud: any text, except that text with a colon in it must be a URI, such ashttps://auth.example.com. They "are compared as case-sensitive strings with no transformations or canonicalizations applied".https://auth.example.com/, with a slash at the end, is a different issuer fromhttps://auth.example.com, and the orders API rejected it in all eight languages. The one exception this tutorial found is .NET's audience check, which by default ignores a slash at the end of the audience: itsIgnoreTrailingSlashWhenValidatingAudiencesetting starts outtrue. - NumericDate, for
exp,nbfandiat: "the number of seconds from 1970-01-01T00:00:00Z UTC until the specified UTC date/time, ignoring leap seconds", which is Unix time.1796057873is 30 November 2026 at 16:57:53 UTC. It counts seconds, not milliseconds, and the difference matters in JavaScript, whereDate.now()returns milliseconds.
jti is a plain string, compared exactly like the other three.
Who Made the Token: iss
iss names the issuer: the service that created and signed the token. Sign-in services use their own address, such as https://auth.example.com. RFC 8725, the JWT best-practice standard, describes OpenID Connect issuers this way: "issuer values are "https" URLs that reference a JSON metadata document that contains a "jwks_uri" value that is an "https" URL from which the issuer's keys are retrieved".
That ties the issuer to its keys, and section 3.8 of RFC 8725 makes it a rule: "When a JWT contains an "iss" (issuer) claim, the application MUST validate that the cryptographic keys used for the cryptographic operations in the JWT belong to the issuer. If they do not, the application MUST reject the JWT."
In this tutorial every service shares one HMAC key, so the key alone can't tell two issuers apart, and the orders API compares iss with the one issuer it trusts. That's also why a shared key is risky: the run shows a token from a staging sign-in service that has the production key by mistake. Later tutorials give each issuer its own key pair, which is how real systems keep issuers apart.
Who the Token Is For: aud
aud names the audience: the API or APIs the token was made for. Section 4.1.3 of RFC 7519 puts the check on the receiving side: "Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the "aud" claim when this claim is present, then the JWT MUST be rejected."
The value is usually one string, but it can be an array of strings when a token is meant for several APIs. An API accepts a token when its own name is anywhere in the array, and the orders API accepted a two-item aud in all eight languages.
The audience is what stops a token made for one API from working at another. Section 3.9 of RFC 8725 explains it: "If the same issuer can issue JWTs that are intended for use by more than one relying party or application, the JWT MUST contain an "aud" (audience) claim that can be used to determine whether the JWT is being used by an intended party or was substituted by an attacker at an unintended party." The same section says the API "MUST validate the audience value".
Whoever holds a billing token, whether a buggy client, the billing API itself or someone who copied it, could send it to the orders API. Its signature is valid and its issuer is trusted. Only aud says it was never meant for the orders API.
Who the Token Is About: sub
sub names the subject, usually the user the token speaks for. Section 4.1.2 of RFC 7519 only requires it to be unique within its issuer: "The subject value MUST either be scoped to be locally unique in the context of the issuer or be globally unique."
So user-42 from one issuer and user-42 from another can be two different people. An API that accepts tokens from more than one issuer keeps each user's record under the pair of iss and sub, never under sub alone, and never under an email address the token happens to carry. RFC 8725 adds that the application "MUST validate that the subject value corresponds to a valid subject and/or issuer-subject pair at the application".
When the Token Counts: exp, nbf and iat
Three claims hold times, all as NumericDate:
expis "the expiration time on or after which the JWT MUST NOT be accepted for processing".nbfis "the time before which the JWT MUST NOT be accepted for processing". A token can be made now and start counting later.iatis "the time at which the JWT was issued. This claim can be used to determine the age of the JWT."
The standard allows "some small leeway, usually no more than a few minutes, to account for clock skew" between servers. This tutorial sets iat and nbf to the moment the token is made and exp 15 minutes later. Expiry, Not-Before and Clock Skew (coming soon) covers how each library checks the times, how much leeway it allows, and what happens to a token that has no exp at all.
Which Token It Is: jti
jti gives one token an ID of its own. Section 4.1.7 asks for an ID that is practically never repeated: "The identifier value MUST be assigned in a manner that ensures that there is a negligible probability that the same value will be accidentally assigned to a different data object; if the application uses multiple issuers, collisions MUST be prevented among values produced by different issuers as well."
A random UUID does that. A version 4 UUID has 122 random bits, and seven of the eight languages make one with a single call. PHP has no UUID function, so the PHP program uses 16 random bytes written as hexadecimal, which has 128.
The standard adds that "The "jti" claim can be used to prevent the JWT from being replayed." That takes a list of the IDs already used, kept until their tokens expire, so a token presented a second time can be refused. A library can't keep that list for you, because it has to last between requests. Refresh Token Rotation and Reuse Detection (coming soon) and Revoke Tokens and Log Out (coming soon) use jti that way.
The Example
The program plays every part at once:
- The sign-in service,
https://auth.example.com, makes tokens for Zara, whose user ID isuser-42. Each token carries all seven claims: its issuer,sub, an audience,iatandnbfset to now,exp15 minutes later, and a fresh randomjti. - The orders API,
https://orders.example.com, checks each token's signature, algorithm and times, as in Create and Verify a JWT in Code, and now also checks thatissis its own sign-in service and thataudnames the orders API.
The sign-in service makes three tokens and hands each to the orders API:
- The orders token, for the orders API. It should be accepted.
- The billing token, made by the same sign-in service with the same key, but for
https://billing.example.com. - The staging token, for the orders API, but made by
https://auth.staging.example.com, a test copy of the sign-in service that was given the production key by mistake.
The program prints the orders token, the seven claims the orders API accepted, and why it rejected the other two.
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 registered-claims and cd registered-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 registered-claims
cd registered-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/registered-claims/package.json:
{
"name": "registered-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 903ms
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": "registered-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.18"
}
}
uv init --no-package registered-claims
cd registered-claims
uv add pyjwt
uv init --no-package registered-claimscreates the project in a newregistered-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 `registered-claims` at `/Users/Shared/you/registered-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 457ms
Prepared 1 package in 268ms
Installed 1 package in 2ms
+ pyjwt==2.15.1
dotnet new console -o registered-claims
cd registered-claims
dotnet package add Microsoft.IdentityModel.JsonWebTokens
dotnet new console -o registered-claimscreates a console app in a newregistered-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/registered-claims/registered-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/registered-claims/registered-claims.csproj'.
info : PackageReference for package 'Microsoft.IdentityModel.JsonWebTokens' version '8.23.0' added to file '/Users/Shared/you/registered-claims/registered-claims.csproj'.
info : Generating MSBuild file /Users/Shared/you/registered-claims/obj/registered-claims.csproj.nuget.g.targets.
info : Writing assets file to disk. Path: /Users/Shared/you/registered-claims/obj/project.assets.json
log : Restored /Users/Shared/you/registered-claims/registered-claims.csproj (in 3.37 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 registered-claims
cd registered-claims
Maven, Java's build tool, reads a project from a file named pom.xml. Create it in the registered-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>registered-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. Leavejjwt-implout, and the code still compiles, but the program stops withUnable to load class named [io.jsonwebtoken.impl.security.KeysBridge]: see the fix for a missing jjwt-impl. 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. Because the class is set in the plugin'sconfiguration,-Dexec.mainClasson the command line can't run another one: a pom property instead of the configuration fixes that.
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 24690 auto-discovered prefixes for remote repository central (prefixes-central.txt)
[INFO]
[INFO] -------------------< com.example:registered-claims >--------------------
[INFO] Building registered-claims 1.0.0
[INFO] from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- dependency:3.11.0:tree (default-cli) @ registered-claims ---
[INFO] com.example:registered-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: 9.966 s
[INFO] Finished at: 2026-11-30T16:58:52Z
[INFO] ------------------------------------------------------------------------
jackson-databind:jar:2.23.0 is the version the jackson-bom entry asked for.
mkdir registered-claims
cd registered-claims
go mod init example.com/registered-claims
go get github.com/golang-jwt/jwt/v5
go mod init example.com/registered-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/registered-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 registered-claims
cd registered-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 registered-claims
cd registered-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/registered-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 registered-claims
cd registered-claims
cargo add jsonwebtoken --features rust_crypto
cargo add serde --features derive
cargo add uuid --features v4
cargo new registered-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.uuidwithv4makes random UUIDs, which Step 3 uses forjti. Rust's standard library has no UUIDs.
Creating binary (application) `registered-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
Updating crates.io index
Adding uuid v1.29.3 to dependencies
Features:
+ rng
+ std
+ v4
- arbitrary
- borsh
- bytemuck
- fast-rng
- js
- macro-diagnostics
- md5
- rng-getrandom
- rng-rand
- serde
- sha1
- slog
- uuid-rng-internal-lib
- v1
- v3
- v5
- v6
- v7
- v8
- zerocopy
Updating crates.io index
Locking 1 package to highest Rust 1.100.1 compatible version
Adding uuid v1.29.3
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 Creates a Token with All Seven 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 the two values the orders API trusts: its own sign-in service, ISSUER, and its own address, ORDERS_API. Then comes the sign-in service's function. It takes the key, an issuer, an audience and a user ID, and returns a token with all seven claims. The comment next to each claim says which job it does.
- 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';
// The sign-in service's job: a token with all seven registered claims.
async function createToken(key, issuer, audience, userId) {
const now = Math.floor(Date.now() / 1000);
return new SignJWT()
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.setIssuer(issuer) // iss: who made the token
.setSubject(userId) // sub: who the token is about
.setAudience(audience) // aud: who the token is for
.setIssuedAt(now) // iat: when it was made
.setNotBefore(now) // nbf: the time it starts to count
.setExpirationTime(now + 15 * 60) // exp: the time it stops counting
.setJti(crypto.randomUUID()) // jti: this token's own ID
.sign(key);
}
constdeclares the two constants.Math.floor(Date.now() / 1000)is the current time in seconds:Date.now()counts milliseconds, and a JWT counts seconds.- Each
setmethod writes one claim. Given a number, jose writes it as it is, sosetIssuedAt(now),setNotBefore(now)andsetExpirationTime(now + 15 * 60)put the same second iniatandnbfand a time 900 seconds later inexp. crypto.randomUUID()returns a random UUID.cryptois built into Node.js, so it needs no import.
import base64
import os
import sys
import uuid
from datetime import datetime, timedelta, timezone
import jwt
ISSUER = "https://auth.example.com"
ORDERS_API = "https://orders.example.com"
def create_token(key: bytes, issuer: str, audience: str, user_id: str) -> str:
"""The sign-in service's job: a token with all seven registered claims."""
now = datetime.now(tz=timezone.utc)
payload = {
"iss": issuer, # who made the token
"sub": user_id, # who the token is about
"aud": audience, # who the token is for
"iat": now, # when it was made
"nbf": now, # the time it starts to count
"exp": now + timedelta(minutes=15), # the time it stops counting
"jti": str(uuid.uuid4()), # this token's own ID
}
return jwt.encode(payload, key, algorithm="HS256")
ISSUERandORDERS_APIare written in capital letters, which in Python marks a value the program never changes.- The payload is a dictionary with all seven claims.
nowis adatetime, andjwt.encodeturns thedatetimevalues iniat,nbfandexpinto the whole seconds a JWT stores. str(uuid.uuid4())makes a random UUID and turns it into text.
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
const string Issuer = "https://auth.example.com";
const string OrdersApi = "https://orders.example.com";
// The sign-in service's job: a token with all seven registered claims.
static string CreateToken(byte[] key, string issuer, string audience, string userId)
{
var now = DateTime.UtcNow;
var descriptor = new SecurityTokenDescriptor
{
Issuer = issuer, // iss: who made the token
Audience = audience, // aud: who the token is for
IssuedAt = now, // iat: when it was made
NotBefore = now, // nbf: the time it starts to count
Expires = now.AddMinutes(15), // exp: the time it stops counting
Claims = new Dictionary<string, object>
{
["sub"] = userId, // sub: who the token is about
["jti"] = Guid.NewGuid().ToString(), // jti: this token's own ID
},
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256),
};
return new JsonWebTokenHandler().CreateToken(descriptor);
}
const stringdeclares the two constants.SecurityTokenDescriptorhas a property for five of the seven claims:Issuer,Audience,IssuedAt,NotBeforeandExpires.subandjtigo in itsClaimsdictionary.Guid.NewGuid()makes a random UUID, which .NET calls a GUID.- 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.UUID;
import javax.crypto.SecretKey;
public class Main {
static final String ISSUER = "https://auth.example.com";
static final String ORDERS_API = "https://orders.example.com";
// The sign-in service's job: a token with all seven registered claims.
static String createToken(SecretKey key, String issuer, String audience, String userId) {
Instant now = Instant.now();
Instant expires = now.plus(Duration.ofMinutes(15));
return Jwts.builder()
.issuer(issuer) // iss: who made the token
.subject(userId) // sub: who the token is about
.audience().add(audience).and() // aud: who the token is for
.issuedAt(Date.from(now)) // iat: when it was made
.notBefore(Date.from(now)) // nbf: the time it starts to count
.expiration(Date.from(expires)) // exp: the time it stops counting
.id(UUID.randomUUID().toString()) // jti: this token's own ID
.signWith(key, Jwts.SIG.HS256)
.compact();
}
static finalmakesISSUERandORDERS_APIconstants.- jjwt has a builder method for each claim:
issuer,subject,issuedAt,notBefore,expirationandid, which writesjti.audience()opens a small builder foraud:addadds one audience andand()returns to the token. issuedAt,notBeforeandexpirationtake ajava.util.Date, soDate.fromconverts eachInstant.UUID.randomUUID().toString()makes a random UUID as text.
package main
import (
"encoding/base64"
"fmt"
"os"
"strings"
"time"
"uuid"
"github.com/golang-jwt/jwt/v5"
)
const (
issuer = "https://auth.example.com"
ordersAPI = "https://orders.example.com"
)
// createToken does the sign-in service's job: a token with all seven registered claims.
func createToken(key []byte, iss, aud, userID string) (string, error) {
now := time.Now()
expires := now.Add(15 * time.Minute)
claims := jwt.RegisteredClaims{
Issuer: iss, // iss: who made the token
Subject: userID, // sub: who the token is about
Audience: jwt.ClaimStrings{aud}, // aud: who the token is for
IssuedAt: jwt.NewNumericDate(now), // iat: when it was made
NotBefore: jwt.NewNumericDate(now), // nbf: the time it starts to count
ExpiresAt: jwt.NewNumericDate(expires), // exp: the time it stops counting
ID: uuid.New().String(), // jti: this token's own ID
}
return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(key)
}
const ( … )declares the two constants together.jwt.RegisteredClaimsis golang-jwt's struct for the seven claims.Audienceis a list of strings, sojwt.ClaimStrings{aud}makes a list with one item, andjwt.NewNumericDateturns atime.Timeinto a NumericDate.uuidis a package of Go's standard library since Go 1.27.uuid.New()makes a random UUID, andString()writes it as text.
<?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';
// The sign-in service's job: a token with all seven registered claims.
function createToken(string $key, string $issuer, string $audience, string $userId): string
{
$now = time();
$payload = [
'iss' => $issuer, // who made the token
'sub' => $userId, // who the token is about
'aud' => $audience, // who the token is for
'iat' => $now, // when it was made
'nbf' => $now, // the time it starts to count
'exp' => $now + 15 * 60, // the time it stops counting
'jti' => bin2hex(random_bytes(16)), // this token's own ID
];
return JWT::encode($payload, $key, 'HS256');
}
constat the top of the file declares the two constants.- The payload is an array with all seven claims, and
time()is the current Unix time. - PHP has no UUID function, so
bin2hex(random_bytes(16))makes the ID: 16 random bytes written as 32 hexadecimal characters.
require 'jwt'
require 'securerandom'
ISSUER = 'https://auth.example.com'
ORDERS_API = 'https://orders.example.com'
# The sign-in service's job: a token with all seven registered claims.
def create_token(key, issuer, audience, user_id)
now = Time.now.to_i
payload = {
iss: issuer, # who made the token
sub: user_id, # who the token is about
aud: audience, # who the token is for
iat: now, # when it was made
nbf: now, # the time it starts to count
exp: now + (15 * 60), # the time it stops counting
jti: SecureRandom.uuid # this token's own ID
}
JWT.encode(payload, key, 'HS256')
end
- A name that starts with a capital letter is a constant in Ruby.
- The payload is a hash with all seven claims, and
Time.now.to_iis the current Unix time. SecureRandom.uuidmakes a random UUID.require 'securerandom'loads it.
use std::time::{SystemTime, UNIX_EPOCH};
use jsonwebtoken::errors::Error;
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
const ISSUER: &str = "https://auth.example.com";
const ORDERS_API: &str = "https://orders.example.com";
/// The seven registered claims.
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
iss: String, // who made the token
sub: String, // who the token is about
aud: String, // who the token is for
iat: u64, // when it was made
nbf: u64, // the time it starts to count
exp: u64, // the time it stops counting
jti: String, // this token's own ID
}
/// The sign-in service's job: a token with all seven registered claims.
fn create_token(
key: &EncodingKey,
issuer: &str,
audience: &str,
user_id: &str,
) -> 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: audience.to_owned(),
iat: now,
nbf: now,
exp: now + 15 * 60,
jti: Uuid::new_v4().to_string(),
};
encode(&Header::new(Algorithm::HS256), &claims, key)
}
constdeclares the two constants, each a&str.Claimshas a field for each of the seven claims. serde writes the struct as the payload's JSON, so each field's name becomes a claim name.Uuid::new_v4()from theuuidcrate makes a random UUID, andto_string()writes it as text.
Step 4: Check the Issuer and the Audience
Next, the orders API. It verifies a token as the earlier tutorials did: the signature with the shared key, only HS256, and the times. On top of that, it now checks that iss is ISSUER and that aud names ORDERS_API, and it rejects a token that leaves either claim out. Each library does that its own way:
- 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;
}
- The
issuerandaudienceoptions ofjwtVerifyturn on both checks. jose rejects a token whoseissisn'tISSUER, whoseauddoesn't nameORDERS_API, or that leaves out either claim. - Without the
audienceoption, jose doesn't look ataudat all.
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)
issuerandaudienceturn on both checks, and PyJWT rejects a token that leaves either claim out.- Pass
audiencewhenever the token has anaud: PyJWT rejects such a token withInvalid audiencewhen you don't say which audience you are.
// The orders API's check: the signature and the times, then the issuer and audience.
static async Task<IDictionary<string, object>> 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 result.Claims;
}
ValidIssuerandValidAudiencegive the two values to compare. IdentityModel checks the issuer and the audience by default, which is why the earlier tutorials, whose tokens had neither claim, turned both checks off withValidateIssuer = falseandValidateAudience = false.result.Claimsholds the verified token's claims, by name.
// 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();
}
requireIssuerandrequireAudiencetell the parser which values to expect. jjwt rejects a token whose claim is different or missing.
// verifyForOrders is the orders API's check: the signature and the times,
// then the issuer and audience.
func verifyForOrders(key []byte, token string) (*jwt.RegisteredClaims, error) {
claims := &jwt.RegisteredClaims{}
_, 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
}
jwt.WithIssuerandjwt.WithAudienceturn on both checks. golang-jwt's documentation says that when you expect an issuer, "we decided to REQUIRE the existence of the claim", and the same goes for the audience.jwt.RegisteredClaimsreceives the claims, so the function returns 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;
}
- php-jwt checks the signature,
exp,nbfandiat, but it never looks atissoraud, so the function checks them itself afterJWT::decode. $claims->iss ?? nullgivesnullwhen the token has noiss, and!==compares exactly, so a missing or different issuer fails.audcan be one string or an array.(array)turns a string into an array with one item and leaves an array as it is, andin_array(ORDERS_API, $audiences, true)checks that the orders API is in it, again comparing exactly.- The function throws
UnexpectedValueException, the class php-jwt's own exceptions extend, so onecatchhandles every rejection.
# 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
iss:andaud:give the values to expect, andverify_iss: trueandverify_aud: trueturn the checks on. Both checks are off by default, and without theverify_options, ruby-jwt accepted a token from the staging issuer for the billing API.JWT.decodereturns the payload and the header, and_headertakes the header without using it.
/// 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, and check nbf too: both are off by default.
validation.set_required_spec_claims(&["exp", "iss", "aud"]);
validation.validate_nbf = true;
let data = decode::<Claims>(token, key, &validation)?;
Ok(data.claims)
}
set_issuerandset_audiencetake the accepted values as a list, here with one item each.- jsonwebtoken checks
issandaudonly when the token has them.set_required_spec_claimsmakes it reject a token that leaves them out, and because it replaces the default list, which holds onlyexp, the call listsexpagain. validate_nbfisfalseby default, so the line after it turns thenbfcheck on.let mutmakesvalidationchangeable, which the calls and the assignment need.
Step 5: Print the Claims and Put It Together
The last piece prints the seven claims of an accepted token, reports what the orders API made of each token, and makes the three tokens:
- Node.js
- Python
- C#
- Java
- Go
- PHP
- Ruby
- Rust
// Print each registered claim of a verified token.
function showClaims(claims) {
console.log(` iss: ${claims.iss}`);
console.log(` sub: ${claims.sub}`);
console.log(` aud: ${claims.aud}`);
console.log(` iat: ${claims.iat}`);
console.log(` nbf: ${claims.nbf}`);
console.log(` exp: ${claims.exp}`);
console.log(` jti: ${claims.jti}`);
}
// Show what the orders API makes of one token.
async function report(key, label, token) {
try {
const claims = await verifyForOrders(key, token);
console.log(`${label} accepted:`);
showClaims(claims);
} 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 orders = await createToken(key, ISSUER, ORDERS_API, 'user-42');
const billing = await createToken(key, ISSUER, 'https://billing.example.com', 'user-42');
const staging = await createToken(key, 'https://auth.staging.example.com', ORDERS_API, 'user-42');
console.log(`Orders token: ${orders}`);
await report(key, 'Orders token', orders);
await report(key, 'Billing token', billing);
await report(key, 'Staging token', staging);
reportcatches jose's errors, which all extendJOSEError, and prints their message.- The billing token has the right issuer and the billing API's audience. The staging token has the orders API's audience and the staging issuer.
def show_claims(claims: dict) -> None:
"""Print each registered claim of a verified token."""
print(f" iss: {claims['iss']}")
print(f" sub: {claims['sub']}")
print(f" aud: {claims['aud']}")
print(f" iat: {claims['iat']}")
print(f" nbf: {claims['nbf']}")
print(f" exp: {claims['exp']}")
print(f" jti: {claims['jti']}")
def report(key: bytes, label: str, token: str) -> None:
"""Show what the orders API makes of one token."""
try:
claims = verify_for_orders(key, token)
print(f"{label} accepted:")
show_claims(claims)
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)
orders = create_token(key, ISSUER, ORDERS_API, "user-42")
billing = create_token(key, ISSUER, "https://billing.example.com", "user-42")
staging = create_token(key, "https://auth.staging.example.com", ORDERS_API, "user-42")
print(f"Orders token: {orders}")
report(key, "Orders token", orders)
report(key, "Billing token", billing)
report(key, "Staging token", staging)
if __name__ == "__main__":
main()
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 orders = CreateToken(key, Issuer, OrdersApi, "user-42");
var billing = CreateToken(key, Issuer, "https://billing.example.com", "user-42");
var staging = CreateToken(key, "https://auth.staging.example.com", OrdersApi, "user-42");
Console.WriteLine($"Orders token: {orders}");
await ReportAsync(key, "Orders token", orders);
await ReportAsync(key, "Billing token", billing);
await ReportAsync(key, "Staging token", staging);
return 0;
// Print each registered claim of a verified token.
static void ShowClaims(IDictionary<string, object> claims)
{
Console.WriteLine($" iss: {claims["iss"]}");
Console.WriteLine($" sub: {claims["sub"]}");
Console.WriteLine($" aud: {claims["aud"]}");
Console.WriteLine($" iat: {claims["iat"]}");
Console.WriteLine($" nbf: {claims["nbf"]}");
Console.WriteLine($" exp: {claims["exp"]}");
Console.WriteLine($" jti: {claims["jti"]}");
}
// Show what the orders API makes of one token.
static async Task ReportAsync(byte[] key, string label, string token)
{
try
{
var claims = await VerifyForOrdersAsync(key, token);
Console.WriteLine($"{label} accepted:");
ShowClaims(claims);
}
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. - The program prints the exception's type, which names the check that failed.
// Print each registered claim of a verified token.
static void showClaims(Claims claims) {
System.out.println(" iss: " + claims.getIssuer());
System.out.println(" sub: " + claims.getSubject());
System.out.println(" aud: " + claims.getAudience());
System.out.println(" iat: " + claims.getIssuedAt().toInstant().getEpochSecond());
System.out.println(" nbf: " + claims.getNotBefore().toInstant().getEpochSecond());
System.out.println(" exp: " + claims.getExpiration().toInstant().getEpochSecond());
System.out.println(" jti: " + claims.getId());
}
// Show what the orders API makes of one token.
static void report(SecretKey key, String label, String token) {
try {
Claims claims = verifyForOrders(key, token);
System.out.println(label + " accepted:");
showClaims(claims);
} 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 orders = createToken(key, ISSUER, ORDERS_API, "user-42");
String billing = createToken(key, ISSUER, "https://billing.example.com", "user-42");
String staging = createToken(key, "https://auth.staging.example.com", ORDERS_API, "user-42");
System.out.println("Orders token: " + orders);
report(key, "Orders token", orders);
report(key, "Billing token", billing);
report(key, "Staging token", staging);
}
}
getAudience()returns a set of strings, so the program printsaudin brackets.getIssuedAt(),getNotBefore()andgetExpiration()return dates, and.toInstant().getEpochSecond()turns each into seconds.
// showClaims prints each registered claim of a verified token.
func showClaims(claims *jwt.RegisteredClaims) {
fmt.Printf(" iss: %s\n", claims.Issuer)
fmt.Printf(" sub: %s\n", claims.Subject)
fmt.Printf(" aud: %s\n", strings.Join(claims.Audience, ", "))
fmt.Printf(" iat: %d\n", claims.IssuedAt.Unix())
fmt.Printf(" nbf: %d\n", claims.NotBefore.Unix())
fmt.Printf(" exp: %d\n", claims.ExpiresAt.Unix())
fmt.Printf(" jti: %s\n", claims.ID)
}
// report shows what the orders API makes of one token.
func report(key []byte, label, token string) {
claims, err := verifyForOrders(key, token)
if err != nil {
fmt.Printf("%s rejected: %v\n", label, err)
return
}
fmt.Printf("%s accepted:\n", label)
showClaims(claims)
}
// 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)
}
orders, err := createToken(key, issuer, ordersAPI, "user-42")
if err != nil {
fail("Could not create the token:", err)
}
billing, err := createToken(key, issuer, "https://billing.example.com", "user-42")
if err != nil {
fail("Could not create the token:", err)
}
staging, err := createToken(key, "https://auth.staging.example.com", ordersAPI, "user-42")
if err != nil {
fail("Could not create the token:", err)
}
fmt.Printf("Orders token: %s\n", orders)
report(key, "Orders token", orders)
report(key, "Billing token", billing)
report(key, "Staging token", staging)
}
strings.Jointurns the audience list back into one string, and.Unix()turns each NumericDate into seconds.
// Print each registered claim of a verified token.
function showClaims(stdClass $claims): void
{
echo " iss: {$claims->iss}\n";
echo " sub: {$claims->sub}\n";
echo " aud: {$claims->aud}\n";
echo " iat: {$claims->iat}\n";
echo " nbf: {$claims->nbf}\n";
echo " exp: {$claims->exp}\n";
echo " jti: {$claims->jti}\n";
}
// Show what the orders API makes of one token.
function report(string $key, string $label, string $token): void
{
try {
$claims = verifyForOrders($key, $token);
echo "{$label} accepted:\n";
showClaims($claims);
} 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);
}
$orders = createToken($key, ISSUER, ORDERS_API, 'user-42');
$billing = createToken($key, ISSUER, 'https://billing.example.com', 'user-42');
$staging = createToken($key, 'https://auth.staging.example.com', ORDERS_API, 'user-42');
echo "Orders token: {$orders}\n";
report($key, 'Orders token', $orders);
report($key, 'Billing token', $billing);
report($key, 'Staging token', $staging);
reportcatchesUnexpectedValueException, which covers php-jwt's rejections and the two the function throws itself.
# Print each registered claim of a verified token.
def show_claims(claims)
puts " iss: #{claims['iss']}"
puts " sub: #{claims['sub']}"
puts " aud: #{claims['aud']}"
puts " iat: #{claims['iat']}"
puts " nbf: #{claims['nbf']}"
puts " exp: #{claims['exp']}"
puts " jti: #{claims['jti']}"
end
# Show what the orders API makes of one token.
def report(key, label, token)
claims = verify_for_orders(key, token)
puts "#{label} accepted:"
show_claims(claims)
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')
orders = create_token(key, ISSUER, ORDERS_API, 'user-42')
billing = create_token(key, ISSUER, 'https://billing.example.com', 'user-42')
staging = create_token(key, 'https://auth.staging.example.com', ORDERS_API, 'user-42')
puts "Orders token: #{orders}"
report(key, 'Orders token', orders)
report(key, 'Billing token', billing)
report(key, 'Staging token', staging)
rescuesits directly in the method, withoutbegin, and catchesJWT::DecodeError, which every ruby-jwt rejection extends.
/// Print each registered claim of a verified token.
fn show_claims(claims: &Claims) {
println!(" iss: {}", claims.iss);
println!(" sub: {}", claims.sub);
println!(" aud: {}", claims.aud);
println!(" iat: {}", claims.iat);
println!(" nbf: {}", claims.nbf);
println!(" exp: {}", claims.exp);
println!(" jti: {}", claims.jti);
}
/// Show what the orders API makes of one token.
fn report(key: &DecodingKey, label: &str, token: &str) {
match verify_for_orders(key, token) {
Ok(claims) => {
println!("{label} accepted:");
show_claims(&claims);
}
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 orders = create_token(&encoding_key, ISSUER, ORDERS_API, "user-42")?;
let billing = create_token(
&encoding_key,
ISSUER,
"https://billing.example.com",
"user-42",
)?;
let staging = create_token(
&encoding_key,
"https://auth.staging.example.com",
ORDERS_API,
"user-42",
)?;
println!("Orders token: {orders}");
report(&decoding_key, "Orders token", &orders);
report(&decoding_key, "Billing token", &billing);
report(&decoding_key, "Staging token", &staging);
Ok(())
}
reportmatches on the result: theOkarm prints the claims and theErrarm prints why the token was rejected.
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
Orders token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiJ1c2VyLTQyIiwiYXVkIjoiaHR0cHM6Ly9vcmRlcnMuZXhhbXBsZS5jb20iLCJpYXQiOjE3OTYwNTc4NzMsIm5iZiI6MTc5NjA1Nzg3MywiZXhwIjoxNzk2MDU4NzczLCJqdGkiOiI4ODFhOTIxYS1lNzU1LTRlODMtOWEyMS1iZDdlNTNmZmVlZTQifQ.2uCz8jYl1GurfHEAWa15ikX2nCpvo7U8J6fchkQ7ifg
Orders token accepted:
iss: https://auth.example.com
sub: user-42
aud: https://orders.example.com
iat: 1796057873
nbf: 1796057873
exp: 1796058773
jti: 881a921a-e755-4e83-9a21-bd7e53ffeee4
Billing token rejected: unexpected "aud" claim value
Staging token rejected: unexpected "iss" claim value

uv run main.py
Orders token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiJ1c2VyLTQyIiwiYXVkIjoiaHR0cHM6Ly9vcmRlcnMuZXhhbXBsZS5jb20iLCJpYXQiOjE3OTYwNTc4ODYsIm5iZiI6MTc5NjA1Nzg4NiwiZXhwIjoxNzk2MDU4Nzg2LCJqdGkiOiI5YjdiMDgzMy1lNTlmLTQxOWUtOTQ3MS03NzM0MWI0OGNhZDAifQ.BivVSnglKI6K7WcpVY7cDt7ZpD2evHGwoF7dFxhA5iM
Orders token accepted:
iss: https://auth.example.com
sub: user-42
aud: https://orders.example.com
iat: 1796057886
nbf: 1796057886
exp: 1796058786
jti: 9b7b0833-e59f-419e-9471-77341b48cad0
Billing token rejected: Audience doesn't match
Staging token rejected: Invalid issuer

dotnet run
Orders token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJodHRwczovL29yZGVycy5leGFtcGxlLmNvbSIsImlzcyI6Imh0dHBzOi8vYXV0aC5leGFtcGxlLmNvbSIsImV4cCI6MTc5NjA1ODgwNiwiaWF0IjoxNzk2MDU3OTA2LCJuYmYiOjE3OTYwNTc5MDYsInN1YiI6InVzZXItNDIiLCJqdGkiOiI4MjU5Njc4OS0wZTgxLTQ5ZjEtYjUxMi0yZjIzYTMxNDM5ZjIifQ._L0YY-WvZGfN2g8cUgqvx9NKEzhLFVdGl91PxuLtHr8
Orders token accepted:
iss: https://auth.example.com
sub: user-42
aud: https://orders.example.com
iat: 1796057906
nbf: 1796057906
exp: 1796058806
jti: 82596789-0e81-49f1-b512-2f23a31439f2
Billing token rejected: SecurityTokenInvalidAudienceException
Staging token rejected: SecurityTokenInvalidIssuerException

mvn -q compile exec:java
Orders token: eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiJ1c2VyLTQyIiwiYXVkIjpbImh0dHBzOi8vb3JkZXJzLmV4YW1wbGUuY29tIl0sImlhdCI6MTc5NjA1Nzk0MCwibmJmIjoxNzk2MDU3OTQwLCJleHAiOjE3OTYwNTg4NDAsImp0aSI6IjQzNDExMjU5LTk2ZGYtNDcyZS1hMWQ4LWVkOTdkNzRjYzBhMCJ9.LVshrECjTSiEr7s0pxNHWUKvWQG2KFtFf9sT4B-_Rjk
Orders token accepted:
iss: https://auth.example.com
sub: user-42
aud: [https://orders.example.com]
iat: 1796057940
nbf: 1796057940
exp: 1796058840
jti: 43411259-96df-472e-a1d8-ed97d74cc0a0
Billing token rejected: Missing expected 'https://orders.example.com' value in 'aud' claim [https://billing.example.com].
Staging token rejected: Expected iss claim to be: https://auth.example.com, but was: https://auth.staging.example.com.

-q keeps Maven quiet, compile builds the code and exec:java runs the class named in pom.xml.
go run .
Orders token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiJ1c2VyLTQyIiwiYXVkIjpbImh0dHBzOi8vb3JkZXJzLmV4YW1wbGUuY29tIl0sImV4cCI6MTc5NjA1ODg3MywibmJmIjoxNzk2MDU3OTczLCJpYXQiOjE3OTYwNTc5NzMsImp0aSI6IjIwMWIwMjlkLTczNDItNDRhYi1hYmQ1LTlkMDY4MDA2MGIzMiJ9.wWmAVtPqdMbmWCo4bBgv3OuptZh0glCSlwtsrsO6ByE
Orders token accepted:
iss: https://auth.example.com
sub: user-42
aud: https://orders.example.com
iat: 1796057973
nbf: 1796057973
exp: 1796058873
jti: 201b029d-7342-44ab-abd5-9d0680060b32
Billing token rejected: token has invalid claims: token has invalid audience
Staging token rejected: token has invalid claims: token has invalid issuer

php main.php
Orders token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiJ1c2VyLTQyIiwiYXVkIjoiaHR0cHM6Ly9vcmRlcnMuZXhhbXBsZS5jb20iLCJpYXQiOjE3OTYwNTc5OTUsIm5iZiI6MTc5NjA1Nzk5NSwiZXhwIjoxNzk2MDU4ODk1LCJqdGkiOiJhOWNlM2E5Mzc2YjcwNGJkZjExOTdjM2RiMWE2ZmYxZSJ9.oUr6WvCdvyF67EOcqcNK0ozk7QHj8UsVBjuAH4cFjVU
Orders token accepted:
iss: https://auth.example.com
sub: user-42
aud: https://orders.example.com
iat: 1796057995
nbf: 1796057995
exp: 1796058895
jti: a9ce3a9376b704bdf1197c3db1a6ff1e
Billing token rejected: Invalid audience
Staging token rejected: Invalid issuer

bundle exec ruby main.rb
Orders token: eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiJ1c2VyLTQyIiwiYXVkIjoiaHR0cHM6Ly9vcmRlcnMuZXhhbXBsZS5jb20iLCJpYXQiOjE3OTYwNTgwMTMsIm5iZiI6MTc5NjA1ODAxMywiZXhwIjoxNzk2MDU4OTEzLCJqdGkiOiIyZjYzNGNlZC1mNjNhLTRmZGUtYTk3My05MjcwNjI5OWZiY2QifQ.PV3msItlSCqae7WocbcGklvEu_FDlZqKhu3POLd4oB0
Orders token accepted:
iss: https://auth.example.com
sub: user-42
aud: https://orders.example.com
iat: 1796058013
nbf: 1796058013
exp: 1796058913
jti: 2f634ced-f63a-4fde-a973-92706299fbcd
Billing token rejected: Invalid audience. Expected https://orders.example.com, received https://billing.example.com
Staging token rejected: Invalid issuer. Expected ["https://auth.example.com"], received https://auth.staging.example.com

cargo run -q
Orders token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiJ1c2VyLTQyIiwiYXVkIjoiaHR0cHM6Ly9vcmRlcnMuZXhhbXBsZS5jb20iLCJpYXQiOjE3OTYwNTgwNTEsIm5iZiI6MTc5NjA1ODA1MSwiZXhwIjoxNzk2MDU4OTUxLCJqdGkiOiI1YTRlOGFkYy0yM2MwLTQ1ZjgtYTU3NC02ZDE2YzQxYmYzNGMifQ.jZX0msGj4ZbLDty7sTNO1yywwg6qHvag5SeJUBzQO-A
Orders token accepted:
iss: https://auth.example.com
sub: user-42
aud: https://orders.example.com
iat: 1796058051
nbf: 1796058051
exp: 1796058951
jti: 5a4e8adc-23c0-45f8-a574-6d16c41bf34c
Billing token rejected: InvalidAudience
Staging token rejected: InvalidIssuer

Your token, times and IDs will differ, because the program makes new ones 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';
// The sign-in service's job: a token with all seven registered claims.
async function createToken(key, issuer, audience, userId) {
const now = Math.floor(Date.now() / 1000);
return new SignJWT()
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.setIssuer(issuer) // iss: who made the token
.setSubject(userId) // sub: who the token is about
.setAudience(audience) // aud: who the token is for
.setIssuedAt(now) // iat: when it was made
.setNotBefore(now) // nbf: the time it starts to count
.setExpirationTime(now + 15 * 60) // exp: the time it stops counting
.setJti(crypto.randomUUID()) // jti: this token's own ID
.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 each registered claim of a verified token.
function showClaims(claims) {
console.log(` iss: ${claims.iss}`);
console.log(` sub: ${claims.sub}`);
console.log(` aud: ${claims.aud}`);
console.log(` iat: ${claims.iat}`);
console.log(` nbf: ${claims.nbf}`);
console.log(` exp: ${claims.exp}`);
console.log(` jti: ${claims.jti}`);
}
// Show what the orders API makes of one token.
async function report(key, label, token) {
try {
const claims = await verifyForOrders(key, token);
console.log(`${label} accepted:`);
showClaims(claims);
} 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 orders = await createToken(key, ISSUER, ORDERS_API, 'user-42');
const billing = await createToken(key, ISSUER, 'https://billing.example.com', 'user-42');
const staging = await createToken(key, 'https://auth.staging.example.com', ORDERS_API, 'user-42');
console.log(`Orders token: ${orders}`);
await report(key, 'Orders token', orders);
await report(key, 'Billing token', billing);
await report(key, 'Staging token', staging);

import base64
import os
import sys
import uuid
from datetime import datetime, timedelta, timezone
import jwt
ISSUER = "https://auth.example.com"
ORDERS_API = "https://orders.example.com"
def create_token(key: bytes, issuer: str, audience: str, user_id: str) -> str:
"""The sign-in service's job: a token with all seven registered claims."""
now = datetime.now(tz=timezone.utc)
payload = {
"iss": issuer, # who made the token
"sub": user_id, # who the token is about
"aud": audience, # who the token is for
"iat": now, # when it was made
"nbf": now, # the time it starts to count
"exp": now + timedelta(minutes=15), # the time it stops counting
"jti": str(uuid.uuid4()), # this token's own ID
}
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 each registered claim of a verified token."""
print(f" iss: {claims['iss']}")
print(f" sub: {claims['sub']}")
print(f" aud: {claims['aud']}")
print(f" iat: {claims['iat']}")
print(f" nbf: {claims['nbf']}")
print(f" exp: {claims['exp']}")
print(f" jti: {claims['jti']}")
def report(key: bytes, label: str, token: str) -> None:
"""Show what the orders API makes of one token."""
try:
claims = verify_for_orders(key, token)
print(f"{label} accepted:")
show_claims(claims)
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)
orders = create_token(key, ISSUER, ORDERS_API, "user-42")
billing = create_token(key, ISSUER, "https://billing.example.com", "user-42")
staging = create_token(key, "https://auth.staging.example.com", ORDERS_API, "user-42")
print(f"Orders token: {orders}")
report(key, "Orders token", orders)
report(key, "Billing token", billing)
report(key, "Staging token", staging)
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";
// 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 orders = CreateToken(key, Issuer, OrdersApi, "user-42");
var billing = CreateToken(key, Issuer, "https://billing.example.com", "user-42");
var staging = CreateToken(key, "https://auth.staging.example.com", OrdersApi, "user-42");
Console.WriteLine($"Orders token: {orders}");
await ReportAsync(key, "Orders token", orders);
await ReportAsync(key, "Billing token", billing);
await ReportAsync(key, "Staging token", staging);
return 0;
// The sign-in service's job: a token with all seven registered claims.
static string CreateToken(byte[] key, string issuer, string audience, string userId)
{
var now = DateTime.UtcNow;
var descriptor = new SecurityTokenDescriptor
{
Issuer = issuer, // iss: who made the token
Audience = audience, // aud: who the token is for
IssuedAt = now, // iat: when it was made
NotBefore = now, // nbf: the time it starts to count
Expires = now.AddMinutes(15), // exp: the time it stops counting
Claims = new Dictionary<string, object>
{
["sub"] = userId, // sub: who the token is about
["jti"] = Guid.NewGuid().ToString(), // jti: this token's own ID
},
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<IDictionary<string, object>> 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 result.Claims;
}
// Print each registered claim of a verified token.
static void ShowClaims(IDictionary<string, object> claims)
{
Console.WriteLine($" iss: {claims["iss"]}");
Console.WriteLine($" sub: {claims["sub"]}");
Console.WriteLine($" aud: {claims["aud"]}");
Console.WriteLine($" iat: {claims["iat"]}");
Console.WriteLine($" nbf: {claims["nbf"]}");
Console.WriteLine($" exp: {claims["exp"]}");
Console.WriteLine($" jti: {claims["jti"]}");
}
// Show what the orders API makes of one token.
static async Task ReportAsync(byte[] key, string label, string token)
{
try
{
var claims = await VerifyForOrdersAsync(key, token);
Console.WriteLine($"{label} accepted:");
ShowClaims(claims);
}
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.UUID;
import javax.crypto.SecretKey;
public class Main {
static final String ISSUER = "https://auth.example.com";
static final String ORDERS_API = "https://orders.example.com";
// The sign-in service's job: a token with all seven registered claims.
static String createToken(SecretKey key, String issuer, String audience, String userId) {
Instant now = Instant.now();
Instant expires = now.plus(Duration.ofMinutes(15));
return Jwts.builder()
.issuer(issuer) // iss: who made the token
.subject(userId) // sub: who the token is about
.audience().add(audience).and() // aud: who the token is for
.issuedAt(Date.from(now)) // iat: when it was made
.notBefore(Date.from(now)) // nbf: the time it starts to count
.expiration(Date.from(expires)) // exp: the time it stops counting
.id(UUID.randomUUID().toString()) // jti: this token's own ID
.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 each registered claim of a verified token.
static void showClaims(Claims claims) {
System.out.println(" iss: " + claims.getIssuer());
System.out.println(" sub: " + claims.getSubject());
System.out.println(" aud: " + claims.getAudience());
System.out.println(" iat: " + claims.getIssuedAt().toInstant().getEpochSecond());
System.out.println(" nbf: " + claims.getNotBefore().toInstant().getEpochSecond());
System.out.println(" exp: " + claims.getExpiration().toInstant().getEpochSecond());
System.out.println(" jti: " + claims.getId());
}
// Show what the orders API makes of one token.
static void report(SecretKey key, String label, String token) {
try {
Claims claims = verifyForOrders(key, token);
System.out.println(label + " accepted:");
showClaims(claims);
} 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 orders = createToken(key, ISSUER, ORDERS_API, "user-42");
String billing = createToken(key, ISSUER, "https://billing.example.com", "user-42");
String staging = createToken(key, "https://auth.staging.example.com", ORDERS_API, "user-42");
System.out.println("Orders token: " + orders);
report(key, "Orders token", orders);
report(key, "Billing token", billing);
report(key, "Staging token", staging);
}
}

package main
import (
"encoding/base64"
"fmt"
"os"
"strings"
"time"
"uuid"
"github.com/golang-jwt/jwt/v5"
)
const (
issuer = "https://auth.example.com"
ordersAPI = "https://orders.example.com"
)
// createToken does the sign-in service's job: a token with all seven registered claims.
func createToken(key []byte, iss, aud, userID string) (string, error) {
now := time.Now()
expires := now.Add(15 * time.Minute)
claims := jwt.RegisteredClaims{
Issuer: iss, // iss: who made the token
Subject: userID, // sub: who the token is about
Audience: jwt.ClaimStrings{aud}, // aud: who the token is for
IssuedAt: jwt.NewNumericDate(now), // iat: when it was made
NotBefore: jwt.NewNumericDate(now), // nbf: the time it starts to count
ExpiresAt: jwt.NewNumericDate(expires), // exp: the time it stops counting
ID: uuid.New().String(), // jti: this token's own ID
}
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) (*jwt.RegisteredClaims, error) {
claims := &jwt.RegisteredClaims{}
_, 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 each registered claim of a verified token.
func showClaims(claims *jwt.RegisteredClaims) {
fmt.Printf(" iss: %s\n", claims.Issuer)
fmt.Printf(" sub: %s\n", claims.Subject)
fmt.Printf(" aud: %s\n", strings.Join(claims.Audience, ", "))
fmt.Printf(" iat: %d\n", claims.IssuedAt.Unix())
fmt.Printf(" nbf: %d\n", claims.NotBefore.Unix())
fmt.Printf(" exp: %d\n", claims.ExpiresAt.Unix())
fmt.Printf(" jti: %s\n", claims.ID)
}
// report shows what the orders API makes of one token.
func report(key []byte, label, token string) {
claims, err := verifyForOrders(key, token)
if err != nil {
fmt.Printf("%s rejected: %v\n", label, err)
return
}
fmt.Printf("%s accepted:\n", label)
showClaims(claims)
}
// 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)
}
orders, err := createToken(key, issuer, ordersAPI, "user-42")
if err != nil {
fail("Could not create the token:", err)
}
billing, err := createToken(key, issuer, "https://billing.example.com", "user-42")
if err != nil {
fail("Could not create the token:", err)
}
staging, err := createToken(key, "https://auth.staging.example.com", ordersAPI, "user-42")
if err != nil {
fail("Could not create the token:", err)
}
fmt.Printf("Orders token: %s\n", orders)
report(key, "Orders token", orders)
report(key, "Billing token", billing)
report(key, "Staging token", staging)
}

<?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';
// The sign-in service's job: a token with all seven registered claims.
function createToken(string $key, string $issuer, string $audience, string $userId): string
{
$now = time();
$payload = [
'iss' => $issuer, // who made the token
'sub' => $userId, // who the token is about
'aud' => $audience, // who the token is for
'iat' => $now, // when it was made
'nbf' => $now, // the time it starts to count
'exp' => $now + 15 * 60, // the time it stops counting
'jti' => bin2hex(random_bytes(16)), // this token's own ID
];
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 each registered claim of a verified token.
function showClaims(stdClass $claims): void
{
echo " iss: {$claims->iss}\n";
echo " sub: {$claims->sub}\n";
echo " aud: {$claims->aud}\n";
echo " iat: {$claims->iat}\n";
echo " nbf: {$claims->nbf}\n";
echo " exp: {$claims->exp}\n";
echo " jti: {$claims->jti}\n";
}
// Show what the orders API makes of one token.
function report(string $key, string $label, string $token): void
{
try {
$claims = verifyForOrders($key, $token);
echo "{$label} accepted:\n";
showClaims($claims);
} 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);
}
$orders = createToken($key, ISSUER, ORDERS_API, 'user-42');
$billing = createToken($key, ISSUER, 'https://billing.example.com', 'user-42');
$staging = createToken($key, 'https://auth.staging.example.com', ORDERS_API, 'user-42');
echo "Orders token: {$orders}\n";
report($key, 'Orders token', $orders);
report($key, 'Billing token', $billing);
report($key, 'Staging token', $staging);

require 'jwt'
require 'securerandom'
ISSUER = 'https://auth.example.com'
ORDERS_API = 'https://orders.example.com'
# The sign-in service's job: a token with all seven registered claims.
def create_token(key, issuer, audience, user_id)
now = Time.now.to_i
payload = {
iss: issuer, # who made the token
sub: user_id, # who the token is about
aud: audience, # who the token is for
iat: now, # when it was made
nbf: now, # the time it starts to count
exp: now + (15 * 60), # the time it stops counting
jti: SecureRandom.uuid # this token's own ID
}
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 each registered claim of a verified token.
def show_claims(claims)
puts " iss: #{claims['iss']}"
puts " sub: #{claims['sub']}"
puts " aud: #{claims['aud']}"
puts " iat: #{claims['iat']}"
puts " nbf: #{claims['nbf']}"
puts " exp: #{claims['exp']}"
puts " jti: #{claims['jti']}"
end
# Show what the orders API makes of one token.
def report(key, label, token)
claims = verify_for_orders(key, token)
puts "#{label} accepted:"
show_claims(claims)
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')
orders = create_token(key, ISSUER, ORDERS_API, 'user-42')
billing = create_token(key, ISSUER, 'https://billing.example.com', 'user-42')
staging = create_token(key, 'https://auth.staging.example.com', ORDERS_API, 'user-42')
puts "Orders token: #{orders}"
report(key, 'Orders token', orders)
report(key, 'Billing token', billing)
report(key, 'Staging token', staging)

use std::time::{SystemTime, UNIX_EPOCH};
use jsonwebtoken::errors::Error;
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
const ISSUER: &str = "https://auth.example.com";
const ORDERS_API: &str = "https://orders.example.com";
/// The seven registered claims.
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
iss: String, // who made the token
sub: String, // who the token is about
aud: String, // who the token is for
iat: u64, // when it was made
nbf: u64, // the time it starts to count
exp: u64, // the time it stops counting
jti: String, // this token's own ID
}
/// The sign-in service's job: a token with all seven registered claims.
fn create_token(
key: &EncodingKey,
issuer: &str,
audience: &str,
user_id: &str,
) -> 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: audience.to_owned(),
iat: now,
nbf: now,
exp: now + 15 * 60,
jti: Uuid::new_v4().to_string(),
};
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, and check nbf too: both are off by default.
validation.set_required_spec_claims(&["exp", "iss", "aud"]);
validation.validate_nbf = true;
let data = decode::<Claims>(token, key, &validation)?;
Ok(data.claims)
}
/// Print each registered claim of a verified token.
fn show_claims(claims: &Claims) {
println!(" iss: {}", claims.iss);
println!(" sub: {}", claims.sub);
println!(" aud: {}", claims.aud);
println!(" iat: {}", claims.iat);
println!(" nbf: {}", claims.nbf);
println!(" exp: {}", claims.exp);
println!(" jti: {}", claims.jti);
}
/// Show what the orders API makes of one token.
fn report(key: &DecodingKey, label: &str, token: &str) {
match verify_for_orders(key, token) {
Ok(claims) => {
println!("{label} accepted:");
show_claims(&claims);
}
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 orders = create_token(&encoding_key, ISSUER, ORDERS_API, "user-42")?;
let billing = create_token(
&encoding_key,
ISSUER,
"https://billing.example.com",
"user-42",
)?;
let staging = create_token(
&encoding_key,
"https://auth.staging.example.com",
ORDERS_API,
"user-42",
)?;
println!("Orders token: {orders}");
report(&decoding_key, "Orders token", &orders);
report(&decoding_key, "Billing token", &billing);
report(&decoding_key, "Staging token", &staging);
Ok(())
}

What the Run Shows
- The orders token passed every check, and its seven claims came back exactly as the sign-in service wrote them:
iatandnbfare the same second,expis 900 seconds later, andjtiis a new random ID. - The billing token had a valid signature. It came from the right issuer, signed with the right key. Only the audience check stopped it, which is the substitution RFC 8725 warns about.
- The staging token had a valid signature too, because the staging service had the production key. Only the issuer check stopped it. Checking
isscaught the mistake, and giving each issuer its own key would have made it impossible. - The libraries don't write
audthe same way. jjwt and golang-jwt write it as an array even when there's one audience, which is why the Java program printed it in brackets. The other six write the string they're given. - .NET put the claims in another order, with
audfirst, as decoding its token shows. Order doesn't matter in JSON, and every library reads the claims by name.
How Each Library Checks iss and aud
Every library could check both claims, but they don't agree on what happens when you leave something out. This table comes from running each library against extra tokens made for the purpose:
| Language | Library | Check the issuer and audience with | A token without iss or aud | A token with aud when you set no audience |
|---|---|---|---|---|
| Node.js | jose | issuer and audience options of jwtVerify | Rejected: missing required "aud" claim | Accepted: aud is ignored |
| Python | PyJWT | issuer= and audience= | Rejected: Token is missing the "aud" claim | Rejected: Invalid audience |
| C# | JsonWebTokenHandler | ValidIssuer and ValidAudience, checked by default | Rejected: IDX10211 for the issuer, IDX10206 for the audience | Rejected: IDX10208, for every token |
| Java | jjwt | requireIssuer and requireAudience | Rejected: Missing 'aud' claim | Accepted: aud is ignored |
| Go | golang-jwt | jwt.WithIssuer and jwt.WithAudience | Rejected: aud claim is required | Accepted: aud is ignored |
| PHP | php-jwt | Nothing: your code compares the claims | Whatever your code does | Accepted: aud is ignored |
| Ruby | jwt | iss: and aud:, with verify_iss: true and verify_aud: true | Rejected: received <none> | Accepted: aud is ignored |
| Rust | jsonwebtoken | set_issuer and set_audience | Accepted, unless the claims are in set_required_spec_claims | Rejected: InvalidAudience |
Two columns deserve a second look. In Rust, setting an issuer and an audience still lets through a token that has neither claim, which is why Step 4 lists them as required. And in Python, Rust and C#, a token with an aud fails until you say which audience you are, while the other five libraries ignore aud unless you ask. An API built on one of those five can forget the audience check and never notice.
Which Claims to Require
Require every claim your API relies on, so a token without it is turned away instead of slipping past a check that only runs when the claim is there. For the orders API, that's iss and aud, which Step 4 requires, exp, so no token lasts forever, and sub, if the API looks the user up by it.
Libraries let you require a claim in different ways, and some not at all:
| Language | Library | Make a claim required | A token without exp, by default |
|---|---|---|---|
| Node.js | jose | requiredClaims: ['exp', 'sub'] | Accepted |
| Python | PyJWT | options={"require": ["exp", "sub"]} | Accepted |
| C# | JsonWebTokenHandler | RequireExpirationTime for exp and RequireAudience for aud, both on by default; other claims in your own code | Rejected: IDX10225 |
| Java | jjwt | Only by expected value, with the require methods; check others in your own code | Accepted |
| Go | golang-jwt | jwt.WithExpirationRequired() and jwt.WithNotBeforeRequired(); others by expected value | Accepted |
| PHP | php-jwt | Nothing: check in your own code | Accepted |
| Ruby | jwt | required_claims: ['exp', 'sub'] | Accepted |
| Rust | jsonwebtoken | set_required_spec_claims(&["exp", "sub"]), for exp, nbf, iss, aud and sub | Rejected: Missing required claim: exp |
Six of the eight libraries accepted a token with no exp under the same checks as this tutorial's orders API. Every token the sign-in service makes has one, so the run never shows it. Expiry, Not-Before and Clock Skew (coming soon) makes the orders API require exp in all eight languages.
What You Can Do Now
- Explain all seven registered claims, what kind of value each one holds and which party checks it.
- Set all seven when you create a token, in any of the eight languages.
- Check a token's issuer and audience, and know which libraries ignore
audunless you ask and which reject it. - Choose which claims your API requires, and make your library require them.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Not checking aud when one sign-in service serves several APIs | A token for one API works at all of them, as the billing token would have | Give each API its own audience and check it on every request |
| Comparing the issuer loosely, or with a slash too many | https://auth.example.com/ and https://auth.example.com are different issuers | Copy the issuer exactly as the sign-in service writes it |
Writing exp, nbf or iat in milliseconds | The token seems to expire tens of thousands of years from now | Divide JavaScript's Date.now() by 1000 and round down |
Ruby: passing iss: and aud: without verify_iss: true and verify_aud: true | ruby-jwt checks neither, and accepted a staging token for the billing API | Add both verify_ options |
Rust: set_issuer and set_audience without set_required_spec_claims | A token with no iss or aud is accepted | List both claims as required |
PHP: expecting php-jwt to check iss or aud | It doesn't, so every issuer and audience passes | Compare both yourself after JWT::decode, as Step 4 does |
| Sharing one key between issuers or environments | A staging token passes in production unless iss is checked | Give each issuer its own key, and check iss as well |
Keeping a user's record under sub alone | Two issuers can each have a user-42, and they're different people | Key users by iss and sub together |
Declaring aud as a single string in a Rust struct when tokens come from jjwt or golang-jwt | They write aud as an array, and decoding fails | Declare aud as Vec<String> |
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 |
Python: jwt.exceptions.InvalidAudienceError: Invalid audience though you didn't ask for an audience check | The token has an aud, and PyJWT rejects it unless you pass audience | Pass your API's audience to jwt.decode |
C#: IDX10208: Unable to validate audience. validationParameters.ValidAudience is null or whitespace and validationParameters.ValidAudiences is null. | IdentityModel checks the audience by default, and there's nothing to compare with | Set ValidAudience |
C#: IDX10214: Audience validation failed. See https://aka.ms/identitymodel/app-context-switches | The token's aud isn't the ValidAudience. Since IdentityModel 8.8.0, this message leaves out the values, so it doesn't say which | Decode the token and compare its aud with ValidAudience |
C#: IDX10205: Issuer validation failed. | The token's iss isn't the ValidIssuer. The message shows both values | Use the issuer exactly as the token has it |
Node.js: unexpected "aud" claim value | The token's aud doesn't name the audience you passed | Check which API the sign-in service made the token for |
Rust: JSON error: invalid type: sequence, expected a string | The token's aud is an array, and the Claims struct says String | Declare aud as Vec<String>, or have the sign-in service write one string |
Rust: InvalidAudience though the audience looks right | set_audience was never called, and jsonwebtoken checks the audience by default | Call set_audience with your API's audience |
Frequently Asked Questions
Does a JWT have to contain the registered claims?
No. RFC 7519 makes every one of them optional and leaves it to each application to decide which ones it uses and requires. In practice, almost every access token carries iss, sub, aud and exp, and an API should require the ones it relies on.
Can aud have more than one value?
Yes. aud can be an array of strings, and an API accepts the token if its own name is one of them. The orders API accepted a token whose aud named both the orders API and the billing API, in all eight languages. golang-jwt also has jwt.WithAllAudiences, which requires every value you list.
What's the difference between iss and aud?
iss says who made the token and aud says who it's for. An API checks that it trusts the first and that it is the second.
Does every library check sub and jti?
Most can compare sub with a value you expect, but an API rarely knows in advance which user to expect, so it reads sub instead of checking it. No library remembers which jti values it has seen, because that needs a list that lasts between requests.
Should iss be a URL?
It can be any string, and a value with a colon in it must be a URI. Sign-in services that follow OpenID Connect use an https URL, because the issuer's keys are found from it.
Why do iat and nbf have the same value here?
Because the sign-in service sets both to the moment it makes the token. nbf can be later than iat for a token that should only start counting in the future, and it can be left out.
Conclusion
The seven registered claims answer the questions every API asks about a token: who made it, who it's about, who it's for, when it counts and which one it is. A valid signature answers none of them, as the billing and staging tokens showed: both were signed correctly with the right key, and only aud and iss kept them out. Set the claims when you create a token, and check and require the ones your API relies on when you verify it.
Next: Custom Claims (coming soon). How to add claims of your own, such as a role, without colliding with anyone else's names.
Additional Resources
- RFC 7519 section 4.1, the registered claim names, and the JSON Web Token Claims registry at IANA, which lists every registered name.
- RFC 8725, JSON Web Token Best Current Practices, sections 3.8 and 3.9.
- SignJWT and JWTVerifyOptions, in the jose documentation.
- Registered Claim Names, in the PyJWT documentation.
- SecurityTokenDescriptor and TokenValidationParameters, on Microsoft Learn, and App Context Switches in IdentityModel, about the audience messages.
- Standard Claims and Claim Assertions, in the jjwt README.
- RegisteredClaims and WithAudience, in the golang-jwt documentation.
- php-jwt, the PHP library.
- Claims, in the ruby-jwt README.
- Validation, in the jsonwebtoken documentation.