Skip to main content

How to Add Custom Claims to a JWT in Java with JJWT

· 9 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
String token = Jwts.builder()
.claim(name, value)
.signWith(key)
.compact();
PartWhat it does
.claim(name, value)Adds one claim. Call it once for each claim. A second call with the same name replaces the value.
nameThe claim's name, a String. Any text works, a URL included.
valueThe value: a String, a number, a boolean, a List, a Map, or a record, which becomes a JSON object. null leaves the claim out.
keyThe 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​

  • A JDK and Maven. This guide uses OpenJDK 25.0.5.1 and Maven 3.10.2.

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:

pom.xml
<?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:

Main.java, which builds a token with issuer, subject, audience and a one-hour expiration, adds the custom claims name, roles as a List and a quota Map under https://photos.example.org/quota, prints the token and its decoded payload, then verifies the token and prints the quota claim.

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 the Map.of(...) under the URL name as a JSON object.
  • The registered claims have their own methods: issuer, subject, audience().add(...).and() and expiration.
  • 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, then getPayload() returns the claims, and claims.get(name) returns one claim's value.

Step 3: Run It​

In the demo folder:

Terminal
mvn -q compile exec:java
Output
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}

A zsh terminal where mvn -q compile exec prints the token, then its payload with iss, sub, aud, exp, name Ada, roles editor and viewer as an array and the quota object with albums 10 and storage_gb 50, then the quota read back in braces.

-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 Java Map, 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 other java.time value, stops the program with Java 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 for claim says an empty value removes the claim. Only null leaves a custom claim out. Add the claim only when it has a value.
  • A java.util.Date is written in milliseconds, {"joined":1767323045000}, while exp and iat are written in seconds.

Common Mistakes​

MistakeWhat happensDo this instead
An Instant or another java.time value as a claimThe token isn't made: Java 8 date/time type ... not supported by defaultSend seconds, with getEpochSecond()
An empty value for a claim that has noneThe token carries "nickname":"", [] or {}Add the claim only when it has a value
A java.util.Date in a custom claimIt's written in milliseconds, unlike exp and iatSend seconds
Calling claim twice with the same nameThe last value wins: .claim("name", "Ada").claim("name", "Grace") wrote {"name":"Grace"}Add each claim once
Using claim("iss", ...) for a registered claimIt 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​

SymptomLikely causeFix
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 in a claimSend the time as seconds
A claim with "", [] or {} in the tokenAn empty value was passed to claimAdd 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.xmlAdd 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​