Skip to main content

Custom Claims

The registered claims say who made a token, who it's about, who it's for and when it counts. They don't say what the user may do. That's the job of custom claims: names and values you choose, such as a user's roles or the plan they pay for. This tutorial explains how to name a custom claim so it can't collide with anyone else's, what a claim can hold, and why an API checks every claim before it uses one. Then it builds a sign-in service that adds three custom claims and an orders API that decides each order from them, in eight languages. Every token in the run carries a valid signature, and the orders API still turns down three of the four orders.

What a Custom Claim Is​

A JWT's payload is a JSON object, and each of its members is a claim: a name and a value. Registered Claims covered the seven names that RFC 7519, the JWT standard, defines itself. Every other claim is up to you. Section 4.2 of the standard puts it plainly: "Claim Names can be defined at will by those using JWTs." This course calls those claims custom claims.

A claim's value isn't limited to text either. Section 2 of RFC 7519 says "A Claim Value can be any JSON value": a string, a number, true or false, null, an array or an object.

Decoded, the payload of a token with custom claims looks like this. It's the token the Python program in this tutorial printed for its user, Zara:

Payload
{
"iss": "https://auth.example.com",
"sub": "user-42",
"aud": "https://orders.example.com",
"iat": 1796284363,
"exp": 1796285263,
"name": "Zara",
"roles": [
"customer",
"beta-tester"
],
"https://orders.example.com/plan": {
"name": "pro",
"order_limit": 500
}
}

The first five claims are registered ones. The last three are custom:

  • name, a string: the user's name, to show on screen.
  • roles, an array of strings: what the user is to the application. Zara is a customer and a beta-tester.
  • https://orders.example.com/plan, an object: the plan Zara pays for, pro, and the most she may order at once, 500.

Three Kinds of Claim Names​

RFC 7519 sorts claim names into three kinds: "There are three classes of JWT Claim Names: Registered Claim Names, Public Claim Names, and Private Claim Names."

KindWhat it isExamples
RegisteredThe seven names RFC 7519 defines in section 4.1iss, sub, aud, exp, nbf, iat, jti
PublicA new name registered in IANA's JSON Web Token Claims registry, or a name that contains a collision-resistant namename and roles from the registry; https://orders.example.com/plan
PrivateAny other name, agreed between the service that makes the token and the one that reads itplan, tenant, permissions

The public kind is how the standard keeps names apart. Section 4.2 says that "in order to prevent collisions, any new Claim Name should either be registered in the IANA "JSON Web Token Claims" registry established by Section 10.1 or be a Public Name: a value that contains a Collision-Resistant Name." A collision-resistant name lives in a namespace where names are "highly unlikely to collide with other names", and the standard gives domain names, object identifiers (OIDs) and UUIDs as examples.

A private name is anything else, such as a short plan. The standard allows it, with a warning in section 4.3: "Unlike Public Claim Names, Private Claim Names are subject to collision and should be used with caution."

Name a Custom Claim So It Can't Collide​

Two parties collide when they use the same claim name for different things. Say the sign-in service also makes tokens for a billing API that uses plan for how often a customer pays, such as "monthly". Then one token can't carry both, and an API that reads plan gets a value that means something else to it.

Three rules keep that from happening:

  1. Look in the registry first. IANA's JSON Web Token Claims registry listed 163 claim names in its 28 October 2026 update, registered by standards such as OpenID Connect. If one of them means what you need, use it with that meaning. The example does that twice. name is OpenID Connect's "Full name". roles comes from SCIM, the standard for user accounts, which defines it in RFC 7643 as "A list of roles for the user that collectively represent who the user is". RFC 9068, the standard for access tokens in JWT format, says that a sign-in service that puts a user's roles, groups or entitlements in an access token "SHOULD use" SCIM's roles, groups and entitlements for them.
  2. Never give a registered name a meaning of your own. Libraries and services that know the registered meaning will read your claim that way. scope, for example, is registered in RFC 8693 as "a JSON string containing a space-separated list of scopes", so a scope that holds an array or anything else breaks the readers that expect the string.
  3. Put everything else in a namespace you control. A URL on your own domain is the usual choice, as in https://orders.example.com/plan: nobody else can make up a claim name under the orders API's own domain. The URL is only a name. Auth0's documentation, which recommends the same, says: "The namespace URL does not have to point to an actual resource. It is only used as an identifier; it will not be called."

A private name like plan is fine when one team controls every service that makes and reads the token, because that team can make sure nobody uses it for anything else. The cost of a URL name is its length: https://orders.example.com/plan takes 31 characters in every token's payload, where plan takes 4.

Check Every Claim Before You Trust It​

An API reads custom claims to make decisions, so it has to be sure of them. Three things make sure:

  • Verify the token first. Anyone can write any claim into a token they make themselves. Only a valid signature from a key you trust says the claims came from your sign-in service unchanged, as Decode vs Verify showed.
  • Then check that each claim you use is there, with the type you expect. A valid signature doesn't promise either. An older version of the sign-in service may not have written the claim yet, another sign-in service may write it differently, and a mistake may change its type. Amazon Cognito's documentation gives the same advice for its own tokens: "Treat every other claim as optional and conditional on how the user authenticated." When a claim is missing or has the wrong type, deny the request.
  • Ignore the claims you don't use. Section 4 of RFC 7519 says that "all claims that are not understood by implementations MUST be ignored." A token can carry claims for other APIs, and the orders API doesn't fail because of them.

The type check matters more than it looks. In JavaScript, Python and Ruby, the usual way to ask whether a list contains customer also works on a string, where it searches the text instead. A token whose roles is the string "not-a-customer" passes that test in all three languages, as When a Claim Has the Wrong Type shows.

What Not to Put in a Claim​

A claim is easy to add, so it's tempting to put everything in the token. Three kinds of data don't belong there:

  • Anything private. The payload is only base64url-encoded, so anyone who holds the token can read every claim, as What Is a JWT? showed. Leave out passwords, keys and personal details the API doesn't need. Section 12 of RFC 7519 says: "Omitting privacy-sensitive information from a JWT is the simplest way of minimizing privacy issues."
  • Anything big. Every claim travels with every request. Firebase Authentication refuses custom claims over 1000 bytes, and its documentation warns that claims used to store data "could cause performance issues because all authenticated requests always contain a Firebase ID token".
  • Anything that must be current. A claim is a copy of what the sign-in service knew when it made the token. If Zara moves to a cheaper plan, the token she already has still says pro until it expires. Firebase documents the same for its own tokens: new custom claims reach a user's token only when the user signs in again or the token is refreshed. Keep tokens short-lived, and look up what must be up to date.

Custom Claims in Real Sign-In Services​

Custom claims aren't only for your own sign-in service. Here is how four well-known ones name theirs and what shape they give them, from each service's own documentation:

Sign-in serviceClaims you'll meetWhat its documentation says
Microsoft Entra IDroles, scp and name in access tokensroles is an "Array of strings", scp is a "String, a space separated list of scopes", and name is for display: "Don't use this value to make authorization decisions."
Auth0The claims you add in an ActionRecommends namespaced names, and warns: "In case of collisions, the transaction won't fail, but your custom claim won't be added to your tokens." The custom claims can take up to 100 KB.
Firebase AuthenticationThe claims you set with the Admin SDK"The payload must not exceed 1000 bytes." New claims reach a user's ID token at the next sign-in or token refresh.
Amazon Cognitocognito:groups and custom: attributes in ID tokenscognito:groups "is always an array, even when the user belongs to a single group". Custom attributes are "always prefixed with custom:", and Cognito writes their values "as strings regardless of attribute type".

The same Entra token carries one list as an array, roles, and another as a single space-separated string, scp. Cognito writes a number attribute as a string. An API has to know the shape of every claim it reads, and check it.

The Example​

The program plays both parts, as in Registered Claims:

  • The sign-in service, https://auth.example.com, makes tokens with five registered claims, iss, sub, aud, iat and an exp 15 minutes later, and three custom ones: name, roles and the plan, under the claim name https://orders.example.com/plan.
  • The orders API, https://orders.example.com, verifies each token as in Registered Claims: the signature, the algorithm, the times, the issuer and the audience. Then it applies one rule to each order: a customer may order up to their plan's limit. Before it uses a claim, it checks that the claim is there and has the type the rule needs.

The sign-in service makes three tokens:

  • Zara's token: user user-42, the roles customer and beta-tester, and the pro plan with an order limit of 500.
  • Sam's token: user user-7, who works in support, with the role support and no plan.
  • Zara's old token: the same user and roles, but made by the sign-in service's previous version, before it added plans. It has no plan claim.

The program prints Zara's token and its custom claims, then places four orders: Zara orders 120 and then 900, Sam orders 120, and Zara's old token orders 120.

Prerequisites​

  • The tools for your language. Pick its tab and check them. These are the versions this tutorial was run with:

Node.js 26, which comes with npm:

Terminal
node --version
npm --version
Output
v26.13.1
12.2.3

Step 1: Create a Project and Add the JWT Library​

Each project lives in its own folder. Where a tab starts with mkdir custom-claims and cd custom-claims, those two commands create the folder and move into it. The other tools create the folder themselves. The commands are the same in every terminal, including PowerShell.

Terminal
mkdir custom-claims
cd custom-claims
npm init -y
npm pkg set type=module
npm install jose
  • npm init -y creates a package.json, the file that describes a Node.js project, without asking any questions.
  • npm pkg set type=module makes the project use ES modules, so the code can load jose with import. npm 12 writes "type": "commonjs" into a new package.json, as the output shows.
  • npm install jose downloads jose into a node_modules folder and adds it to package.json.
Output
Wrote to /Users/Shared/you/custom-claims/package.json:
{
"name": "custom-claims",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"type": "commonjs"
}
added 1 package, and audited 2 packages in 1s
1 package is looking for funding
run `npm fund` for details
found 0 vulnerabilities

package.json now says the project is a module and depends on jose:

package.json
{
"name": "custom-claims",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"type": "module",
"dependencies": {
"jose": "^6.2.19"
}
}

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.

Terminal
export JWT_SECRET=$(openssl rand -base64 32)
echo ${#JWT_SECRET}
Output
44

A zsh terminal where export JWT_SECRET stores the output of openssl rand -base64 32 and echo with a hash sign prints its length, 44 characters.

JWT_SECRET now holds the 32 bytes as 44 characters of base64 text, and the program decodes that text back into the 32 bytes it uses as the key. The length check confirms the variable is set without printing the secret on your screen. The variable lasts until you close this terminal, so run the program from the same window.

Step 3: Write the Code That Adds Custom Claims​

Create the program's file: main.js, main.py, Program.cs, src/main/java/com/example/Main.java, main.go, main.php, main.rb or src/main.rs, depending on your language. Most editors create the folders in the path for you. In Python, C# and Rust, replace what the template put in the file. The code goes in over the next three steps, and the complete file shows it all together.

The file starts with three constants: the issuer and the audience the orders API trusts, as in Registered Claims, and PLAN_CLAIM, the plan claim's name. Then comes the sign-in service's function. It takes the key, a user ID, a name, a list of roles and a plan, and returns a token with the registered claims and the custom ones. A user without a plan gets no plan claim at all.

main.js
import { SignJWT, jwtVerify, errors } from 'jose';

const ISSUER = 'https://auth.example.com';
const ORDERS_API = 'https://orders.example.com';
// A custom claim name on the orders API's own domain, so nobody else's claim can have it.
const PLAN_CLAIM = 'https://orders.example.com/plan';

// The sign-in service's job: the registered claims plus the custom claims the orders API needs.
async function createToken(key, userId, name, roles, plan) {
const claims = {
name, // a string
roles, // an array of strings
};
if (plan) {
claims[PLAN_CLAIM] = plan; // an object: the plan's name and its order limit
}
const now = Math.floor(Date.now() / 1000);
return new SignJWT(claims)
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.setIssuer(ISSUER)
.setSubject(userId)
.setAudience(ORDERS_API)
.setIssuedAt(now)
.setExpirationTime(now + 15 * 60)
.sign(key);
}
  • { name, roles } is short for { name: name, roles: roles }, so each claim takes the name of its variable.
  • The plan claim's name is a URL, which can't be written after a dot, so claims[PLAN_CLAIM] = plan adds it with square brackets. if (plan) skips it when the plan is null.
  • new SignJWT(claims) starts the payload with the custom claims, and the set methods add the registered ones. jose writes each value as JSON: the roles become an array and the plan an object.

Step 4: Verify the Token and Read Its Custom Claims​

The orders API verifies a token exactly as in Registered Claims: the signature with the shared key, only HS256, the times, the issuer and the audience. The second function prints the custom claims of a verified token. It reads each claim by its name, in the form the library hands it back. It's only used for Zara's token, which the program made itself with all three claims, so it doesn't check them. The orders API's rule in Step 5 does.

main.js
// The orders API's check: the signature and the times, then the issuer and audience.
async function verifyForOrders(key, token) {
const { payload } = await jwtVerify(token, key, {
algorithms: ['HS256'],
issuer: ISSUER,
audience: ORDERS_API,
});
return payload;
}

// Print the custom claims of a verified token.
function showClaims(claims) {
const plan = claims[PLAN_CLAIM];
console.log(` name: ${claims.name}`);
console.log(` roles: ${claims.roles.join(', ')}`);
console.log(` plan: ${plan.name}, order limit ${plan.order_limit}`);
}
  • jwtVerify returns the payload as a plain JavaScript object: claims.name, claims.roles, and claims[PLAN_CLAIM] for the name that's a URL.
  • roles comes back as an array, and join(', ') prints its items with a comma between them.

Step 5: Check the Claims, Then Decide​

Now the orders API's rule: a customer may order up to their plan's limit. Before the rule uses a claim, it checks that the claim is there and has the type the rule needs, and it denies the order when it doesn't. That way, a missing claim or a wrong type can never let an order through by accident. Then report prints the decision for one order, and the last part makes the three tokens and places the four orders:

main.js
// The orders API's rule: a customer may order up to their plan's limit.
// A valid signature proves who wrote the claims, not that each one is there
// with the type the rule expects, so the rule checks that first.
function checkOrder(claims, amount) {
const roles = claims.roles;
if (!Array.isArray(roles) || !roles.includes('customer')) {
return 'denied: needs the customer role';
}
const plan = claims[PLAN_CLAIM];
if (typeof plan !== 'object' || plan === null || !Number.isInteger(plan.order_limit)) {
return 'denied: the token has no plan';
}
if (amount > plan.order_limit) {
return `denied: over the ${plan.name} plan's order limit of ${plan.order_limit}`;
}
return 'allowed';
}

// Show what the orders API makes of one order.
async function report(key, label, token, amount) {
try {
const claims = await verifyForOrders(key, token);
console.log(`${label}: ${checkOrder(claims, amount)}`);
} catch (err) {
if (!(err instanceof errors.JOSEError)) throw err;
console.log(`${label}: rejected: ${err.message}`);
}
}

// The key every service shares: 32 random bytes, kept as base64 text in JWT_SECRET.
const secret = process.env.JWT_SECRET;
if (!secret) {
console.error('Set the JWT_SECRET environment variable first.');
process.exit(1);
}
const key = Uint8Array.fromBase64(secret);

const zara = await createToken(key, 'user-42', 'Zara', ['customer', 'beta-tester'], {
name: 'pro',
order_limit: 500,
});
const sam = await createToken(key, 'user-7', 'Sam', ['support'], null);
// A token from the sign-in service's previous version, which didn't add plans yet.
const old = await createToken(key, 'user-42', 'Zara', ['customer', 'beta-tester'], null);
console.log(`Zara's token: ${zara}`);
console.log("Custom claims in Zara's token:");
showClaims(await verifyForOrders(key, zara));

await report(key, 'Zara orders 120', zara, 120);
await report(key, 'Zara orders 900', zara, 900);
await report(key, 'Sam orders 120', sam, 120);
await report(key, "Zara's old token orders 120", old, 120);
  • Array.isArray(roles) is true only for an array, and includes('customer') then looks for an item equal to customer.
  • typeof plan !== 'object' || plan === null turns away anything that isn't an object, null included: typeof null is 'object' in JavaScript. Number.isInteger checks that the limit is a whole number.
  • report catches jose's errors, which all extend JOSEError, and prints their message.

Step 6: Run the Program​

Run the program in the terminal where you set JWT_SECRET:

Terminal
node main.js
Output
Zara's token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiWmFyYSIsInJvbGVzIjpbImN1c3RvbWVyIiwiYmV0YS10ZXN0ZXIiXSwiaHR0cHM6Ly9vcmRlcnMuZXhhbXBsZS5jb20vcGxhbiI6eyJuYW1lIjoicHJvIiwib3JkZXJfbGltaXQiOjUwMH0sImlzcyI6Imh0dHBzOi8vYXV0aC5leGFtcGxlLmNvbSIsInN1YiI6InVzZXItNDIiLCJhdWQiOiJodHRwczovL29yZGVycy5leGFtcGxlLmNvbSIsImlhdCI6MTc5NjI4NDM0OSwiZXhwIjoxNzk2Mjg1MjQ5fQ.RNByZ-W9SAB1-x8Eg4E7kxl7clQzIkg5az1wUDjReRY
Custom claims in Zara's token:
name: Zara
roles: customer, beta-tester
plan: pro, order limit 500
Zara orders 120: allowed
Zara orders 900: denied: over the pro plan's order limit of 500
Sam orders 120: denied: needs the customer role
Zara's old token orders 120: denied: the token has no plan

A zsh terminal where node main.js prints Zara's token and her custom claims, name Zara, roles customer and beta-tester, and the pro plan with an order limit of 500, then allows Zara's order of 120 and denies her order of 900, Sam's order and the order with her old token.

Your token will differ, because the program makes a new one on every run. The rest of the output should match.

The Complete File​

main.js
import { SignJWT, jwtVerify, errors } from 'jose';

const ISSUER = 'https://auth.example.com';
const ORDERS_API = 'https://orders.example.com';
// A custom claim name on the orders API's own domain, so nobody else's claim can have it.
const PLAN_CLAIM = 'https://orders.example.com/plan';

// The sign-in service's job: the registered claims plus the custom claims the orders API needs.
async function createToken(key, userId, name, roles, plan) {
const claims = {
name, // a string
roles, // an array of strings
};
if (plan) {
claims[PLAN_CLAIM] = plan; // an object: the plan's name and its order limit
}
const now = Math.floor(Date.now() / 1000);
return new SignJWT(claims)
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.setIssuer(ISSUER)
.setSubject(userId)
.setAudience(ORDERS_API)
.setIssuedAt(now)
.setExpirationTime(now + 15 * 60)
.sign(key);
}

// The orders API's check: the signature and the times, then the issuer and audience.
async function verifyForOrders(key, token) {
const { payload } = await jwtVerify(token, key, {
algorithms: ['HS256'],
issuer: ISSUER,
audience: ORDERS_API,
});
return payload;
}

// Print the custom claims of a verified token.
function showClaims(claims) {
const plan = claims[PLAN_CLAIM];
console.log(` name: ${claims.name}`);
console.log(` roles: ${claims.roles.join(', ')}`);
console.log(` plan: ${plan.name}, order limit ${plan.order_limit}`);
}

// The orders API's rule: a customer may order up to their plan's limit.
// A valid signature proves who wrote the claims, not that each one is there
// with the type the rule expects, so the rule checks that first.
function checkOrder(claims, amount) {
const roles = claims.roles;
if (!Array.isArray(roles) || !roles.includes('customer')) {
return 'denied: needs the customer role';
}
const plan = claims[PLAN_CLAIM];
if (typeof plan !== 'object' || plan === null || !Number.isInteger(plan.order_limit)) {
return 'denied: the token has no plan';
}
if (amount > plan.order_limit) {
return `denied: over the ${plan.name} plan's order limit of ${plan.order_limit}`;
}
return 'allowed';
}

// Show what the orders API makes of one order.
async function report(key, label, token, amount) {
try {
const claims = await verifyForOrders(key, token);
console.log(`${label}: ${checkOrder(claims, amount)}`);
} catch (err) {
if (!(err instanceof errors.JOSEError)) throw err;
console.log(`${label}: rejected: ${err.message}`);
}
}

// The key every service shares: 32 random bytes, kept as base64 text in JWT_SECRET.
const secret = process.env.JWT_SECRET;
if (!secret) {
console.error('Set the JWT_SECRET environment variable first.');
process.exit(1);
}
const key = Uint8Array.fromBase64(secret);

const zara = await createToken(key, 'user-42', 'Zara', ['customer', 'beta-tester'], {
name: 'pro',
order_limit: 500,
});
const sam = await createToken(key, 'user-7', 'Sam', ['support'], null);
// A token from the sign-in service's previous version, which didn't add plans yet.
const old = await createToken(key, 'user-42', 'Zara', ['customer', 'beta-tester'], null);
console.log(`Zara's token: ${zara}`);
console.log("Custom claims in Zara's token:");
showClaims(await verifyForOrders(key, zara));

await report(key, 'Zara orders 120', zara, 120);
await report(key, 'Zara orders 900', zara, 900);
await report(key, 'Sam orders 120', sam, 120);
await report(key, "Zara's old token orders 120", old, 120);

The complete main.js: the ISSUER, ORDERS_API and PLAN_CLAIM constants, createToken adding name, roles and the plan to SignJWT, verifyForOrders, showClaims, checkOrder checking each claim's type before the order limit, report, and the code that makes three tokens and places four orders.

What the Run Shows​

  • Zara's first order passed every check. Her token is valid, she has the customer role, and 120 is within the pro plan's limit of 500. The orders API decided without looking Zara up anywhere: everything it needed was in the token.
  • Her second order was turned down by the plan, not by the token. Same token, same claims, but 900 is over the limit.
  • Sam's token was valid too, and still denied. A valid signature says the claims are genuine. It doesn't say they allow the order: Sam works in support and isn't a customer.
  • Zara's old token had no plan claim, and the orders API denied the order instead of crashing or letting it through. Tokens outlive the code that made them: a token issued just before a new sign-in service goes live still reaches the API, so the API has to handle a claim that isn't there.
  • Java printed the roles in brackets, because claims.get("roles", List.class) returns a Java List. Every other program joined them with a comma.

How Each Library Reads Custom Claims​

Each library turns the payload's JSON into its own types, and they don't agree on how. This table comes from reading extra tokens made for the purpose, whose custom claims included every JSON type:

LanguageLibraryRead a claim withA JSON array becomesA JSON object becomesA claim the token leaves out
Node.jsjosepayload.roles, or payload[name] for any nameArraya plain objectundefined
PythonPyJWTclaims.get("roles") or claims["roles"]listdictNone from get, a KeyError from []
C#JsonWebTokenHandlerTryGetPayloadValue<T> or GetPayloadValue<T>the type you ask for, such as string[]the type you ask for, such as Dictionary<string, object>false from TryGetPayloadValue; GetPayloadValue throws IDX14304
Javajjwtclaims.get("roles"), or claims.get("roles", List.class)ArrayListLinkedHashMapnull
Gogolang-jwtthe fields of your claims structthe field's type, such as []stringthe field's type, such as *Planthe field's zero value: nil for a slice or a pointer
PHPphp-jwt$claims->roles, or $claims->{$name} for any namearraystdClassnull, with an Undefined property warning unless you use ??
Rubyjwtclaims['roles']ArrayHashnil
Rustjsonwebtokenthe fields of your claims structthe field's type, such as Vec<String>the field's type, such as PlanNone for an Option field; any other field rejects the whole token

Two more differences showed up in the same tokens. golang-jwt also offers jwt.MapClaims, a map you can read claims from without a struct, and it reads every number as a float64, even 500. And jjwt drops a claim whose value is null, so claims.containsKey says the token doesn't have it.

When a Claim Has the Wrong Type​

To see what each library does with a claim of the wrong type, the orders API was handed two more tokens with valid signatures: one whose roles is the string "customer" instead of an array, and one whose order limit is the string "500" instead of a number. Here is what the program from this tutorial decided:

LanguageLibraryroles is the string "customer"order_limit is the string "500"
Node.jsjoseDenied: not an arrayDenied: not a whole number
PythonPyJWTDenied: not a listDenied: not an int
C#JsonWebTokenHandlerAllowed: TryGetPayloadValue<string[]> reads one string as an array of oneDenied: a string, not an int
JavajjwtDenied: not a ListDenied: not an Integer
Gogolang-jwtRejected: cannot unmarshal string into Go struct field Claims.roles of type []stringRejected: cannot unmarshal string into Go struct field Claims.https:~1~1orders.example.com~1plan.order_limit of type int
PHPphp-jwtDenied: not an arrayDenied: not an int
RubyjwtDenied: not an ArrayDenied: not an Integer
RustjsonwebtokenRejected: invalid type: string "customer", expected a sequence at line 1 column 151Rejected: invalid type: string "500", expected u32 at line 1 column 221

Go's message writes each / in the claim's name as ~1, and Rust's ends with the position in the payload's JSON just after the wrong value. Go and Rust reject the whole token before your code sees it, because the claims have to fit the struct you declared. The other six hand your code whatever the token holds, and the checks in Step 5 are what turn the order down. .NET is the one library that lets a single string count as a list. That's still safe for a role, because the role still has to match exactly: a roles of "not-a-customer" became an array holding not-a-customer, and the order was denied.

Without the type checks, three of the eight languages would have let a wrong value through. Given a token whose roles is the string "not-a-customer", roles.includes('customer') in JavaScript, 'customer' in roles in Python and roles.include?('customer') in Ruby are all true, because on a string each of them searches the text. PHP's in_array stops with a TypeError instead, and jjwt's claims.get("roles", List.class) throws a RequiredTypeException.

What You Can Do Now​

  • Tell registered, public and private claim names apart, and give a custom claim a name that can't collide.
  • Add custom claims of any JSON type to a token, in any of the eight languages.
  • Read them back after verifying the token, and check that each one is there with the type your code needs.
  • Decide what belongs in a claim and what the API should look up instead.

Common Mistakes​

MistakeWhat happensDo this instead
Using a short private name such as plan or role across teamsAnother service uses the same name for something else, and an API reads a value meant for anotherUse a registered name with its registered meaning, or a URL on your own domain
Giving a registered name a meaning of your own, such as scope as an arrayLibraries and services that know the registered meaning misread itCheck the IANA registry first, and pick another name
Reading claims before verifying the tokenAnyone can write any claim into a token they make themselvesVerify first, then read
Checking for a role without checking that roles is an arrayIn JavaScript, Python and Ruby, the string "not-a-customer" passes a check for customerCheck the type first, as Step 5 does
Assuming every token has every claimA token from an older sign-in service, like Zara's old token, crashes the code or skips the checkTreat a missing claim as a reason to deny
Putting private data or secrets in a claimAnyone who holds the token can read themLeave them out, and look them up on the server
Putting data that must be current in a claimThe token keeps the old value until it expiresKeep tokens short-lived, and look up what must be current
Making authorization decisions from name or an email addressThey're for display, and they can change or repeatDecide from sub, roles and other claims meant for it
C#: a class or record of your own as a claim valueIdentityModel stops with IDX11025: Cannot serialize object of typeUse a Dictionary<string, object>, as Step 3 does
Go: reading claims into jwt.MapClaims and expecting an intEvery number comes back as a float64Read them into a struct with typed fields, as this tutorial does
Java: an empty string, list or map as a custom claim's valuejjwt keeps it in the token, although its documentation says an empty value removes the claimAdd the claim only when it has a value
PHP: NAN or INF as a claim value, such as the result of fdiv() dividing by zerophp-jwt stops with Unknown JSON error: 7, because JSON can't hold themCheck the number with is_finite() first
Python: float("nan") or float("inf") as a claim valuePyJWT writes NaN or Infinity into the payload, which isn't JSON, and other languages' libraries reject the tokenSend None for "no value"
Rust: a field that isn't an Option for a claim that can be missingThe whole token is rejected with missing field `roles` Make the field an Option

Troubleshooting​

SymptomLikely causeFix
Set the JWT_SECRET environment variable first.Step 2 ran in another terminal, or not at allRun Step 2 again in the terminal where you run the program
C#: System.ArgumentException: IDX11025: Cannot serialize object of type: 'Plan' into property: 'https://orders.example.com/plan'.A claim's value is an object of a class or record of your ownUse a dictionary instead
C#: IDX14304: Claim with name '[PII of type 'System.String' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]' does not exist in the JsonClaimSet.GetPayloadValue asked for a claim the token doesn't haveUse TryGetPayloadValue, as Step 5 does
Go: token is malformed: could not JSON decode claim: json: cannot unmarshal string into Go struct field Claims.roles of type []stringA claim's JSON type doesn't match its field's typeCheck what the sign-in service writes, and give the field the matching type
Rust: JSON error: missing field `roles` at line 1 column 200The token doesn't have a claim whose field isn't an OptionMake the field an Option if the claim can be missing
Rust: JSON error: invalid type: string "customer", expected a sequence at line 1 column 151A claim's JSON type doesn't match its field's typeCheck what the sign-in service writes, and give the field the matching type
PHP: Warning: Undefined property: stdClass::$missing, with the claim's name after the $The code reads a claim the token doesn't haveAdd ?? null, as Step 5 does
PHP: in_array(): Argument #2 ($haystack) must be of type array, string givenroles is a string, not an arrayCheck is_array first, as Step 5 does
PHP: DomainException: Unknown JSON error: 7 from JWT::encodeA claim's value is NAN or INF, which JSON can't holdAdd the claim only when is_finite() says it's a finite number
Python: KeyError with the claim's nameclaims["..."] on a claim the token doesn't haveUse claims.get("...")
Node.js: JWTInvalid: JWT Claims Set must be a top-level JSON object, with a [cause] that shows NaNA Python service wrote float("nan") into a claim with PyJWTSend None instead, and make PyJWT refuse NaN
Java: io.jsonwebtoken.RequiredTypeException: Cannot convert existing claim value of type 'class java.lang.String' to desired type 'interface java.util.List'. JJWT only converts simple String, Date, Long, Integer, Short and Byte types automatically. …, and the message goes onclaims.get(name, List.class) on a claim that isn't a listCheck with instanceof, as Step 5 does
Java: io.jsonwebtoken.io.SerializationException: Cannot serialize JWS Payload to JSON. Cause: Unable to serialize object of type io.jsonwebtoken.impl.DefaultClaims: Java 8 date/time type java.time.Instant not supported by default …, and the message goes onA java.time value, such as an Instant, in a claimSend the time as seconds since 1970

Frequently Asked Questions​

What's the difference between public and private claims?​

A public claim name is either registered in IANA's JSON Web Token Claims registry, such as roles, or contains a collision-resistant name, such as a URL on your own domain. A private claim name is any other name that the sign-in service and the API agree on, such as plan. RFC 7519 warns that private names "are subject to collision and should be used with caution".

Do custom claim names have to be URLs?​

No. A registered name such as name or roles is fine when you use it with its registered meaning, and a private name is fine when one team controls every service that makes and reads the token. A URL on your own domain is the safe choice for everything else.

Are custom claims encrypted?​

No. A signed JWT's payload is only base64url-encoded, so anyone who holds the token can read every claim. The signature only stops them from changing one. Keep private data out of claims, or encrypt the whole token, which JWE: Encrypted JWTs (coming soon) covers.

Can I put a user's permissions in a token?​

Yes, and roles and permissions are the most common custom claims. Remember that they're fixed until the token expires: a user whose role is taken away keeps it until their token runs out. Keep such tokens short-lived.

Should a list of roles be an array or a space-separated string?​

Use an array for roles, which RFC 7643 defines as a list. scope is the registered exception, a single string of names separated by spaces. Whichever shape your sign-in service writes, the API has to read the same one, which is why the orders API checks it.

How many custom claims can a token have?​

The standard sets no limit, but every claim travels with every request, so keep them few and small. Sign-in services set their own limits: Firebase allows 1000 bytes of custom claims, and Auth0 allows 100 KB.

Conclusion​

Custom claims carry what your API needs to make a decision: who the user is to your application and what they may do. Name them so they can't collide, with a registered name in its registered meaning or a URL on your own domain. Then treat every claim, even in a verified token, as a value to check before you use it. The run showed why: Sam's and Zara's old tokens were both signed correctly, and only the checks in Step 5 kept their orders out.

Next: Expiry, Not-Before and Clock Skew (coming soon). How each library checks exp and nbf, how much clock difference it allows, and what happens to a token without exp.

Additional Resources​