How to decode a JWT in Java and get attributes

Last modified date

Comments: 0

Contents

Problem

JWT are used throughout everywhere web development to authenticate users.

But decoding them isn’t straightforward when it is received on the backend.

The solution below shows how to decode a JWT in Java.

Solution

Add the nimbus maven dependency to your Java pom.xml.

<dependency>
    <groupId>com.nimbusds</groupId>
    <artifactId>nimbus-jose-jwt</artifactId>
    <version>8.3</version>
</dependency>

Then create a new decoder class and use the nimbus library to decode the JWT.

The example below shows how to get the sub / subject from the JWT.

To get other attributes, you can find the other functions available on the JWTClaimsSet object in the java doc.

public class Decoder {

  public String decodeJWT(String token) throws ParseException {

    SignedJWT decodedJWT = SignedJWT.parse(token);
    JWTClaimsSet jwtClaimsSet = decodedJWT.getJWTClaimsSet();
    return jwtClaimsSet.getSubject();

  }
}

JakTech

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.