Programming & Development / April 19, 2025

How to Extract and Decode JWT Token Details in Java

Java JWT decode token extract JWT details JWT claims token parsing Base64 Spring Boot authentication JSON Web Token

To extract and read details from a JWT (JSON Web Token) in Java, especially without using any external library, you can decode the token manually using Base64.

✅ JWT Token Format

A JWT typically has three parts separated by dots (.):

css

HEADER.PAYLOAD.SIGNATURE

To read the payload (claims), decode the second part of the token.

✅ Example Code to Extract Payload

java

import java.util.Base64;

public class JwtDecoder {

    public static String decodeJWT(String token) {
        try {
            // Split the token into parts
            String[] parts = token.split("\\.");

            if (parts.length < 2) {
                throw new IllegalArgumentException("Invalid JWT token");
            }

            // JWT structure: parts[0] = header, parts[1] = payload
            String payload = parts[1];

            // Decode the Base64-encoded payload
            byte[] decodedBytes = Base64.getUrlDecoder().decode(payload);
            return new String(decodedBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return "Failed to decode token";
        }
    }

    public static void main(String[] args) {
        String jwtToken = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxIiwic2NvcGVzIjpbeyJhdXRob3JpdHkiOiJjb20u...<snip>...";

        String decodedPayload = decodeJWT(jwtToken);
        System.out.println("Decoded JWT Payload:\n" + decodedPayload);
    }
}

🧠 Output Example

json

{
  "sub": "1",
  "scopes": [
    {
      "authority": "com.accolite.pru.health.AuthApp.model.Role@6eed717f"
    },
    ...
  ],
  "iat": 1724291727,
  "exp": 1724292627
}

🔍 Notes

  • Base64.getUrlDecoder(): JWT uses Base64 URL encoding, not the standard one.
  • No Verification: This method only decodes the token — it does NOT verify the signature or validate the token.
  • Use Libraries for Secure Handling: If you're validating or working with JWTs securely, consider libraries like:
  • Java JWT (by Auth0)
  • Nimbus JOSE + JWT



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