Add JWT library in pom.xml
<!-- pom.xml -->
<!-- JWT Token Creation Library -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
Create JWT Token
public static String generateJWTToken() {
String signatureSecret = "SECRET_VALUE_FOR_SIGNATURE";
Algorithm algorithm = Algorithm.HMAC256(signatureSecret);
Calendar c = Calendar.getInstance();
Date currentDate = c.getTime();
c.add(Calendar.HOUR, 24);
Date expireDate = c.getTime();
String jwtToken = JWT.create()
.withIssuer("smoothprogramming")
.withSubject("demo")
.withAudience("techgeeks")
.withIssuedAt(currentDate)
.withExpiresAt(expireDate)
.withClaim("Claim1", "Value1")
.withClaim("Claim2", "Value2")
.sign(algorithm);
return jwtToken;
}
Verify JWT Token
Verify method verifies and decode the JWT token. If verification fails then it throws an exception.
public static void verifyJWTToken(String jwtToken) {
String signatureSecret = "SECRET_VALUE_FOR_SIGNATURE";
Algorithm algorithm = Algorithm.HMAC256(signatureSecret);
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("smoothprogramming")
.withSubject("demo")
.build();
DecodedJWT decodedJWT = verifier.verify(jwtToken);
System.out.println("Claim1 is "+ decodedJWT.getClaim("Claim1").asString());
System.out.println("Claim2 is "+ decodedJWT.getClaim("Claim2").asString());
}
Decode JWT Token
There are times when you don’t want to verify the token, but want to extract the content of the JWT token. In this case, you dont need a secret to extract JWT token’s content.
public static void decodeJWTToken(String jwtToken) {
DecodedJWT decodedJWT = JWT.decode(jwtToken);
System.out.println("Claim1 is "+ decodedJWT.getClaim("Claim1").asString());
System.out.println("Claim2 is "+ decodedJWT.getClaim("Claim2").asString());
}
Code
Find the code at Github Repo.
References:
https://jwt.io/