Below step-by-step procedure explain how to verify the token using static secret.
Step 1: Get an instance of algorithm
String secret = "secret123";
Algorithm algorithmHS = Algorithm.HMAC256(secret);
Step 2: Get an instance of JWTVerifier
JWTVerifier verifier = JWT.require(algorithmHS).build();
Step 3: Verify the token
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwZXJtaXNzaW9ucyI6WyJlZGl0b3IiLCJub3RpZmllciJdLCJpc3MiOiJhdXRoMCIsIm5hbWUiOiJrcmlzaG5hIiwiZG9tYW4iOiJIUiIsImV4cCI6MTYyMjAzNTkyNywiaWF0IjoxNjIyMDA3MTI3fQ.9cimobXGLxSublYwNWRoKQjOr4Bo65sBhovhCoUD6qM";
DecodedJWT jwt = verifier.verify(token);
Step 4: Extract the token payload
String payload = jwt.getPayload();
Base64.Decoder base64Decoder = Base64.getDecoder();
String tokenPayload = new String(base64Decoder.decode(payload));
Find the below working application.
TokenVerificationUsingStaticSecret.java
package com.sampple.app.examples;
import java.util.Base64;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
public class TokenVerificationUsingStaticSecret {
public static void main(String args[]) {
// Get an instance of algorithm
String secret = "secret123";
Algorithm algorithmHS = Algorithm.HMAC256(secret);
// Get an instance of JWTVerifier
JWTVerifier verifier = JWT.require(algorithmHS).build();
// Verify the token
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwZXJtaXNzaW9ucyI6WyJlZGl0b3IiLCJub3RpZmllciJdLCJpc3MiOiJhdXRoMCIsIm5hbWUiOiJrcmlzaG5hIiwiZG9tYW4iOiJIUiIsImV4cCI6MTYyMjAzNTkyNywiaWF0IjoxNjIyMDA3MTI3fQ.9cimobXGLxSublYwNWRoKQjOr4Bo65sBhovhCoUD6qM";
DecodedJWT jwt = verifier.verify(token);
// Extract the token payload
String payload = jwt.getPayload();
Base64.Decoder base64Decoder = Base64.getDecoder();
String tokenPayload = new String(base64Decoder.decode(payload));
System.out.println(tokenPayload);
}
}
Output
{"permissions":["editor","notifier"],"iss":"auth0","name":"krishna","doman":"HR","exp":1622035927,"iat":1622007127}
You will get an error when the token expires.
Token and decoded information
No comments:
Post a Comment