How to Add Custom Claims to a JWT in Java with JJWT
JJWT adds your own claims to a token with the builder's claim(name, value) method, called once for each claim: .claim("name", "Ada"). Jackson writes each value as JSON, so a List becomes an array and a Map an object, and the verified token gives the values back.
Syntax
String token = Jwts.builder()
.claim(name, value)
.signWith(key)
.compact();
| Part | What it does |
|---|---|
.claim(name, value) | Adds one claim. Call it once for each claim. A second call with the same name replaces the value. |
name | The claim's name, a String. Any text works, a URL included. |
value | The value: a String, a number, a boolean, a List, a Map, or a record, which becomes a JSON object. null leaves the claim out. |
key | The signing key, here an HMAC key made with Keys.hmacShaKeyFor. |
The JJWT README, Custom Claims: "If you need to set one or more custom claims that don't match the standard setter method claims shown above, you can simply call the JwtBuilder claim method one or more times as needed". And: "Each time claim is called, it simply appends the key-value pair to an internal Claims builder, potentially overwriting any existing identically-named key/value pair."
The Example
The example signs a token for a user named Ada, issued by https://login.example.org for https://photos.example.org, that expires in an hour. It has three custom claims of three JSON types: name, a string; roles, a list; and https://photos.example.org/quota, a map with an album limit and a storage limit. The last one has a URL as its name, so that no other service's claim can have the same name. The example prints the token and its payload, then verifies the token and reads the quota back.
Prerequisites
Step 1: Create the Project
Create a folder named demo with this pom.xml. JJWT comes in three parts: jjwt-api for your code, and jjwt-impl and jjwt-jackson, which do the work while the program runs:
<?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>demo</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>
Step 2: Write the Code
Create src/main/java/com/example/Main.java:

package com.example;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.crypto.SecretKey;
public class Main {
public static void main(String[] args) {
// The signing key: 32 random bytes, written as base64.
// It's in the code only for this example; a real app loads it from its configuration.
SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64.decode("C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64="));
String token = Jwts.builder()
.issuer("https://login.example.org")
.subject("ada")
.audience().add("https://photos.example.org").and()
.expiration(Date.from(Instant.now().plus(Duration.ofHours(1))))
.claim("name", "Ada") // a string
.claim("roles", List.of("editor", "viewer")) // an array
.claim("https://photos.example.org/quota", Map.of("albums", 10, "storage_gb", 50)) // an object
.signWith(key)
.compact();
System.out.println(token);
// The payload is the token's middle piece, base64url-encoded JSON.
String payload = token.split("\\.")[1];
System.out.println(new String(Decoders.BASE64URL.decode(payload), StandardCharsets.UTF_8));
Claims claims = Jwts.parser()
.verifyWith(key)
.requireIssuer("https://login.example.org")
.requireAudience("https://photos.example.org")
.build()
.parseSignedClaims(token)
.getPayload();
System.out.println(claims.get("https://photos.example.org/quota"));
}
}
.claim("name", "Ada")adds a string claim.List.of("editor", "viewer")is written as a JSON array, and theMap.of(...)under the URL name as a JSON object.- The registered claims have their own methods:
issuer,subject,audience().add(...).and()andexpiration. - The payload lines take the token's middle piece and decode it with JJWT's
Decoders.BASE64URL, to show the claims as JSON. Jwts.parser()checks the signature, the expiry, the issuer and the audience, thengetPayload()returns the claims, andclaims.get(name)returns one claim's value.
Step 3: Run It
In the demo folder:
mvn -q compile exec:java
eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2xvZ2luLmV4YW1wbGUub3JnIiwic3ViIjoiYWRhIiwiYXVkIjpbImh0dHBzOi8vcGhvdG9zLmV4YW1wbGUub3JnIl0sImV4cCI6MTc5NjI5NDIzOSwibmFtZSI6IkFkYSIsInJvbGVzIjpbImVkaXRvciIsInZpZXdlciJdLCJodHRwczovL3Bob3Rvcy5leGFtcGxlLm9yZy9xdW90YSI6eyJhbGJ1bXMiOjEwLCJzdG9yYWdlX2diIjo1MH19.uhZaVmtUvQCd75WE1nvBuz_749B6bq_IjtbjGmnjT90
{"iss":"https://login.example.org","sub":"ada","aud":["https://photos.example.org"],"exp":1796294239,"name":"Ada","roles":["editor","viewer"],"https://photos.example.org/quota":{"albums":10,"storage_gb":50}}
{albums=10, storage_gb=50}

-q keeps Maven quiet, compile builds the program and exec:java runs it. The command is the same in zsh, bash and PowerShell.
What Happened
- The custom claims follow the registered ones in the payload, in the order they were added, each with its JSON type:
"roles":["editor","viewer"]is an array, and the quota is an object. claims.get("https://photos.example.org/quota")printed{albums=10, storage_gb=50}. The JSON object came back as a JavaMap, which prints in braces.
I checked other values too. A long, a double and a boolean became JSON numbers and false. An int[], a String[] and a Set became arrays, a UUID became a string, and a record became an object: {"plan":{"name":"pro","limit":500}}. Three kinds of value behave differently from what you might expect:
- A
java.time.Instant, or any otherjava.timevalue, stops the program withJava 8 date/time type java.time.Instant not supported by default. Send the time as seconds instead. - An empty string, list or map stays in the token as
"",[]or{}, although JJWT's documentation forclaimsays an empty value removes the claim. Onlynullleaves a custom claim out. Add the claim only when it has a value. - A
java.util.Dateis written in milliseconds,{"joined":1767323045000}, whileexpandiatare written in seconds.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
An Instant or another java.time value as a claim | The token isn't made: Java 8 date/time type ... not supported by default | Send seconds, with getEpochSecond() |
| An empty value for a claim that has none | The token carries "nickname":"", [] or {} | Add the claim only when it has a value |
A java.util.Date in a custom claim | It's written in milliseconds, unlike exp and iat | Send seconds |
Calling claim twice with the same name | The last value wins: .claim("name", "Ada").claim("name", "Grace") wrote {"name":"Grace"} | Add each claim once |
Using claim("iss", ...) for a registered claim | It works, but the README recommends "the standard respective type-safe named builder method as this enhances readability" | Use issuer, subject and the other named methods |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
io.jsonwebtoken.io.SerializationException: Cannot serialize JWS Payload to JSON. Cause: Unable to serialize object of type io.jsonwebtoken.impl.DefaultClaims: Java 8 date/time type java.time.Instant not supported by default …, and the message goes on | A java.time value in a claim | Send the time as seconds |
A claim with "", [] or {} in the token | An empty value was passed to claim | Add the claim only when it has a value |
ExceptionInInitializerError: Unable to load class named [io.jsonwebtoken.impl.security.KeysBridge] | jjwt-impl isn't in pom.xml | Add it with runtime scope |
FAQ
Can I add several claims at once?
Yes, with claims(Map). The README, Claims Map: "If you want to add multiple claims at once, you can use JwtBuilder claims(Map) method". A map holding name and sub gave the payload {"name":"Ada","sub":"ada"}.
Why does one claim have a URL as its name?
Short names like quota can collide with another service's claim of the same name. The JWT standard, RFC 7519, says a new claim name should either be registered with IANA or be collision-resistant, and it names domain names as one way to make it so. A URL on a domain you control is such a name.
Conclusion
Call claim(name, value) once for each custom claim, with a value Jackson can write as JSON: strings, numbers, booleans, lists, maps and records. Send times as seconds, leave out claims that have no value, and give claims that other services may see a URL name.
Additional Resources
- Custom Claims and Claims Map, in the JJWT README.
- JwtBuilder, in the JJWT 0.13.0 API documentation.
- RFC 7519 section 4, on registered, public and private claim names.
