Programming & Development / April 19, 2025

How to Extract and Decode JWT Details Using Nimbus JOSE + JWT

Java Nimbus JOSE JWT decode token extract JWT details Nimbus JWT authentication Spring Boot JSON Web Token secure token parsing JWS JWE

The Nimbus JOSE + JWT library is a popular Java library for handling JWT (JSON Web Tokens), JWS (JSON Web Signature), and JWE (JSON Web Encryption). Below is how you can extract and decode JWT details (payload and claims) using Nimbus JOSE + JWT.

✅ Maven Dependency

First, include the Nimbus JOSE + JWT library in your project by adding the Maven dependency in your pom.xml:

xml

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

✅ Example Code to Decode and Extract JWT Details

Here's how to decode and extract JWT details like claims using the Nimbus JOSE + JWT library:

java

import com.nimbusds.jwt.JWT;
import com.nimbusds.jwt.JWTParser;
import com.nimbusds.jwt.JWTClaimsSet;

import java.text.ParseException;

public class JwtDecoder {

    public static void decodeJWT(String token) {
        try {
            // Parse the JWT string into a JWT object
            JWT jwt = JWTParser.parse(token);

            // Extract the JWT claims
            JWTClaimsSet claims = ((com.nimbusds.jwt.SignedJWT) jwt).getJWTClaimsSet();

            // Extract claims from the JWT
            String subject = claims.getSubject();  // 'sub' claim
            String issuer = claims.getIssuer();   // 'iss' claim
            String audience = claims.getAudience().toString(); // 'aud' claim
            String expiration = claims.getExpirationTime().toString(); // 'exp' claim
            String issuedAt = claims.getIssueTime().toString();    // 'iat' claim

            // Print the decoded claims
            System.out.println("Subject: " + subject);
            System.out.println("Issuer: " + issuer);
            System.out.println("Audience: " + audience);
            System.out.println("Expiration: " + expiration);
            System.out.println("Issued At: " + issuedAt);

        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println("Invalid token");
        }
    }

    public static void main(String[] args) {
        String jwtToken = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxIiwiaXNzIjoiY29tLmFjY29saXRlIiwic3ViIjoiMSIsImV4cCI6MTY0MjkzMzk1MywiYXVzIjpbInVzZXIiXX0.fWmmnObSmTln2LHRdnlM_4DdUlkQ8_eJ6zxgd9wBbDg";

        decodeJWT(jwtToken);
    }
}

🧠 Output Example

text

Subject: 1
Issuer: com.accolite
Audience: [user]
Expiration: Sun Dec 10 13:39:53 UTC 2023
Issued At: Sun Dec 10 12:39:53 UTC 2023

🔍 Key Features of Nimbus JOSE + JWT

  • JWT Parsing:
  • The JWTParser.parse(token) method parses a JWT string into a JWT object.
  • Extract Claims:
  • Once parsed, you can extract various JWT claims, including the sub, iss, exp, and iat claims. You can also access custom claims using getClaim("claimName").
  • Claims are extracted using the getJWTClaimsSet() method which returns a JWTClaimsSet.
  • Claims Types:
  • getSubject() - Extracts the sub claim (Subject).
  • getIssuer() - Extracts the iss claim (Issuer).
  • getAudience() - Extracts the aud claim (Audience).
  • getExpirationTime() - Extracts the exp claim (Expiration Time).
  • getIssueTime() - Extracts the iat claim (Issued At).

✅ Signature Verification and Validation

For secure handling of JWTs, you should verify the token's signature. This requires the JWT to be signed with a secret key or public/private key pair. Below is an example of JWT signature verification using Nimbus JOSE + JWT:

java

import com.nimbusds.jose.*;
import com.nimbusds.jwt.*;

import java.text.ParseException;

public class JwtVerifier {

    public static void verifyJWT(String token, String secret) {
        try {
            // Parse the JWT token
            SignedJWT signedJWT = (SignedJWT) JWTParser.parse(token);

            // Verify the signature using a secret key (HMAC)
            JWSVerifier verifier = new MACVerifier(secret);

            // Verify the signature
            if (signedJWT.verify(verifier)) {
                System.out.println("Signature is valid!");

                // Extract the JWT claims
                JWTClaimsSet claims = signedJWT.getJWTClaimsSet();

                // Print claims
                System.out.println("Subject: " + claims.getSubject());
                System.out.println("Issuer: " + claims.getIssuer());

            } else {
                System.out.println("Invalid signature!");
            }

        } catch (ParseException | JOSEException e) {
            e.printStackTrace();
            System.out.println("Error verifying token");
        }
    }

    public static void main(String[] args) {
        String jwtToken = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxIiwiaXNzIjoiY29tLmFjY29saXRlIiwic3ViIjoiMSIsImV4cCI6MTY0MjkzMzk1MywiYXVzIjpbInVzZXIiXX0.fWmmnObSmTln2LHRdnlM_4DdUlkQ8_eJ6zxgd9wBbDg";
        String secretKey = "your-secret-key";

        verifyJWT(jwtToken, secretKey);
    }
}

🔍 Notes

  • Signature Verification:
  • You can use HMAC (HS256, HS512) for symmetric verification or RSA/ECDSA for asymmetric verification. The example uses HMAC (MACVerifier).
  • Token Parsing:
  • You can use JWTParser.parse(token) to parse a JWT string into a SignedJWT or EncryptedJWT object, depending on the type of JWT (signed or encrypted).
  • Claims Extraction:
  • After parsing, the getJWTClaimsSet() method retrieves the claims from the JWT. You can use getSubject(), getIssuer(), and other methods to extract details.
  • Custom Claims:
  • You can retrieve custom claims in the JWT by using getClaim("claimName").



Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex