Skip to main content

How to Verify a JWT in Java with the JJWT Parser

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

JJWT verifies JSON Web Tokens in Java with a parser: Jwts.parser() starts it, verifyWith(key) sets the key, build() makes the parser, and parseSignedClaims(token) checks the token and returns its claims, or throws an exception that says what's wrong.

Syntax​

Syntax
Claims claims = Jwts.parser()
.verifyWith(<key>)
.build()
.parseSignedClaims(<token>)
.getPayload();
PartWhat it does
Jwts.parser()Starts a parser builder.
.verifyWith(<key>)Sets the key that checks signatures: for HS256, the same SecretKey that signed the token.
.build()Makes the parser, which you can keep and reuse.
.parseSignedClaims(<token>)Checks the signature and the time claims, and returns the signed token.
.getPayload()The verified claims, as a Claims object.

From the JJWT Javadoc: parseSignedClaims "Parses the jws argument, expected to be a cryptographically-signed Claims JWS", and on the parser builder, verifyWith(SecretKey key) "Sets the signature verification SecretKey used to verify all encountered JWS signatures."

The Example​

The example signs a token for the user ada with the role reader, then parses it twice: with the key that signed it, and with a different key, the way a token from another app would arrive.

Both keys are 32 random bytes, made with openssl rand -base64 32 and written as base64. They sit in the code only so the example runs as it is. A real application loads its key from configuration and never keeps it in the source.

Prerequisites​

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

Step 1: Create the Project​

JJWT comes as three parts: jjwt-api, which your code uses, and jjwt-impl and jjwt-jackson, which it needs at run time. Create a folder named demo with this pom.xml in it:

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>

jackson-bom makes Maven use the newest Jackson 2 release, because the version jjwt-jackson asks for is old. exec-maven-plugin runs the com.example.Main class.

Step 2: Write the Code​

Inside demo, create the folders src/main/java/com/example and save this as Main.java there:

Main.java, which signs a token for ada with role reader and a 10-minute expiry, parses it with Jwts.parser, verifyWith the key, build and parseSignedClaims, prints the subject and role, then parses it with another key inside try and catch for SignatureException and prints Rejected with the message.

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 io.jsonwebtoken.security.SignatureException;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import javax.crypto.SecretKey;

public class Main {
public static void main(String[] args) {
// Two keys, 32 random bytes each, written as base64.
// They're in the code only for this example; a real app loads its key from its configuration.
SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64.decode("VfosHbT9z3nikPe56UUfKL9Y6mF2oOui09j4GCY0AYs="));
SecretKey otherKey = Keys.hmacShaKeyFor(Decoders.BASE64.decode("rAAk7yhJl8rF7vvQeKOeI2ooYrBw9A45aLuMb44gH78="));

String token = Jwts.builder()
.subject("ada")
.claim("role", "reader")
.expiration(Date.from(Instant.now().plus(Duration.ofMinutes(10))))
.signWith(key)
.compact();

Claims claims = Jwts.parser()
.verifyWith(key)
.build()
.parseSignedClaims(token)
.getPayload();
System.out.println(claims.getSubject() + " " + claims.get("role", String.class));

try {
Jwts.parser().verifyWith(otherKey).build().parseSignedClaims(token);
} catch (SignatureException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}

claims.getSubject() reads sub, and claims.get("role", String.class) reads a custom claim as a String. The SignatureException caught here is the one in io.jsonwebtoken.security.

Step 3: Run It​

From the demo folder:

Terminal
mvn -q compile exec:java
Output
ada reader
Rejected: JWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted.

A zsh terminal where mvn -q compile exec prints ada reader, then Rejected: JWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted.

mvn -q compile exec:java compiles the code and runs it, and -q hides Maven's own messages. With the right key, the parser checked the signature and the expiry and returned the claims. With the other key, the signature didn't match, so it threw.

The Exceptions It Throws​

These came from real runs:

What's wrongExceptionMessage
Signed with another key, or the payload was changedio.jsonwebtoken.security.SignatureExceptionJWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted.
The token has expiredExpiredJwtExceptionJWT expired 60900 milliseconds ago at 2026-11-26T08:44:12.000Z. Current time: 2026-11-26T08:45:12.900Z. Allowed clock skew: 0 milliseconds.
requireSubject("ada"), but the subject is graceIncorrectClaimExceptionExpected sub claim to be: ada, but was: grace.
Not a JWT at allMalformedJwtExceptionInvalid compact JWT string: Compact JWSs must contain exactly 2 period characters, and compact JWEs must contain exactly 4. Found: 0
An unsigned token, "alg":"none"UnsupportedJwtExceptionUnsecured JWSs (those with an 'alg' (Algorithm) header value of 'none') are disallowed by default …

Allow a Little Clock Skew​

The expired-token message shows that the parser allows no clock skew by default. clockSkewSeconds sets it on the parser builder, which "Sets the amount of clock skew in seconds to tolerate when verifying the local time against the exp and nbf claims": with .clockSkewSeconds(60), a token that had expired 30 seconds earlier still parsed.

Common Mistakes​

MistakeWhat happensDo this instead
Wildcard imports of both io.jsonwebtoken.* and io.jsonwebtoken.security.*reference to SignatureException is ambiguous: both packages have oneImport io.jsonwebtoken.security.SignatureException by name
Reading a claim as the wrong type, get("level", String.class) on a numberRequiredTypeException: Cannot convert existing claim value of type 'class java.lang.Integer' to desired type 'class java.lang.String'. …Ask for the type the claim holds, such as Integer.class
Expecting get to fail for a missing claimIt returns nullCheck for null, or use require… on the parser

Troubleshooting​

SymptomLikely causeFix
JWT signature does not match locally computed signatureAnother key signed it, or it was changedVerify with the signing key; reject the token
JWT expired … agoThe token's exp has passedGet a new token, or allow some clockSkewSeconds
Compact JWSs must contain exactly 2 period charactersThe string isn't a JWTCheck what's being passed in

FAQ​

Can I reuse the parser?​

Yes. build() makes a parser you can keep for every token, as long as the key stays the same.

Does the parser check the expiry?​

Yes, whenever the token has an exp claim, with no clock skew unless you set one.

Conclusion​

Jwts.parser().verifyWith(key).build().parseSignedClaims(token).getPayload() returns a token's claims only after its signature and time claims check out. Catch the specific exceptions when you answer each failure differently, and import SignatureException from io.jsonwebtoken.security.

Additional Resources​