The Java JWT library by Auth0 makes it easier to work with JSON Web Tokens (JWTs) in Java, providing tools to decode, verify, and manipulate JWTs securely. Below is how you can extract and decode JWT details (payload and claims) using the Java JWT library by Auth0.
✅ Maven Dependency
First, include the Java JWT library in your project by adding the Maven dependency in your pom.xml
:
xml
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.0.0</version>
</dependency>
✅ Example Code to Decode and Extract JWT Details
java
import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
public class JwtDecoder {
public static void decodeJWT(String token) {
try {
// Decode the JWT (this does not verify the signature)
DecodedJWT decodedJWT = JWT.decode(token);
// Get claims from the decoded JWT
String subject = decodedJWT.getSubject(); // 'sub' claim
String issuer = decodedJWT.getIssuer(); // 'iss' claim
long expiration = decodedJWT.getExpiresAt().getTime(); // 'exp' claim
long issuedAt = decodedJWT.getIssuedAt().getTime(); // 'iat' claim
// Print the decoded claims
System.out.println("Subject: " + subject);
System.out.println("Issuer: " + issuer);
System.out.println("Expiration: " + expiration);
System.out.println("Issued At: " + issuedAt);
// Additional claims can be accessed as needed
System.out.println("Custom Claim 'scopes': " + decodedJWT.getClaim("scopes").asString());
} catch (Exception e) {
e.printStackTrace();
System.out.println("Invalid token");
}
}
public static void main(String[] args) {
String jwtToken = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxIiwic2NvcGVzIjpbeyJhdXRob3JpdHkiOiJjb20u...<snip>...";
decodeJWT(jwtToken);
}
}
🧠 Output Example
text
Subject: 1
Issuer: com.accolite
Expiration: 1724292627
Issued At: 1724291727
Custom Claim 'scopes': [{"authority":"com.accolite.pru.health.AuthApp.model.Role@6eed717f"}]
🔍 Key Features of Java JWT by Auth0
- Decoding JWT:
JWT.decode(token)
decodes the token and returns the DecodedJWT
object.- Extract Claims:
- You can extract standard JWT claims using methods like:
getSubject()
for the sub
claimgetIssuer()
for the iss
claimgetExpiresAt()
for the exp
claimgetIssuedAt()
for the iat
claim- Custom Claims:
- To extract custom claims, you can use
getClaim("claimName")
, which returns the value of the custom claim. - For example,
decodedJWT.getClaim("scopes").asString()
to extract the value of the "scopes" claim. - Signature Verification:
- To verify the token's signature, you need to use a secret or public key. This can be done with methods like
JWT.require(algorithm).build().verify(token)
.
✅ Secure Handling and Verification
While decoding JWT is useful for extracting details, for secure handling, you must verify the token's signature to ensure that it has not been tampered with. Here's how you can verify the token:
java
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
public class JwtVerifier {
public static void verifyJWT(String token, String secret) {
try {
// Set up the algorithm (HMAC256, RS256, etc.)
Algorithm algorithm = Algorithm.HMAC256(secret);
// Verify the token using the algorithm
DecodedJWT decodedJWT = JWT.require(algorithm)
.build()
.verify(token);
// If verification passes, extract claims as needed
String subject = decodedJWT.getSubject();
System.out.println("Verified Subject: " + subject);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Invalid token or signature");
}
}
public static void main(String[] args) {
String jwtToken = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxIiwic2NvcGVzIjpbeyJhdXRob3JpdHkiOiJjb20u...<snip>...";
String secretKey = "your-secret-key";
verifyJWT(jwtToken, secretKey);
}
}
🔍 Notes
- JWT Signature Verification: The code above uses HMAC256 for verification, but you can use other algorithms like RS256 if you're working with asymmetric keys (public/private key pairs).
- Token Expiration: Always check the expiration time (
exp
claim) before trusting a JWT. - Custom Claims: Extracting custom claims is straightforward using
getClaim("claimName")
, but be cautious when processing these values.