Java Quick Trick - Decode JWT Payload

A quick guide on programmatically decoding a JSON Web Token’s payload.

JWT basically consists of three parts separated by dots (.)

  • Header
  • Payload
  • Signing Key

The Header basically consists the type of the token which is JWT and the algorithm that is used to sign this token.

The second part of the token is the payload, which consists of the claims i.e. the information about the user.

The Base64 URL encoded form of the Header and Payload respectively form the 1st and 2nd parts of Json Web Token.

Video guide of the process



 

Steps involved:

Add commons-codec dependency from Apache in pom.xml

1
2
3
4
5
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>

1
String token = "<YOUR JWT TOKEN>";

Split the token based on period . and extract the payload part from the token.

1
String payload = token.split("\\.")[1];

Use Base64 utility to decode the payload.

1
String payloadValue = new String (Base64.decodeBase64(payload));

If you want to use a specific charset like UTF-8, you can use the below snippet.

1
2
3
4
5
try {
String payloadValue = new String(Base64.decodeBase64(payload), "UTF-8");
}catch(UnsupportedEncodingException ex) {
System.err.println(ex.getMessage());
}

Note: Make sure to import the Base64 from the package org.apache.commons.codec.binary.Base64.