Wednesday, 26 May 2021

Java: Program to generate and validate jwt token using static secret

 

JWTWithStaticSecretDemo.java

package com.sampple.app.examples;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

public class JWTWithStaticSecretDemo {
	public static void main(String args[]) {
		String secret = "secret123";

		// Get an instance of algorithm
		Algorithm algorithmHS = Algorithm.HMAC256(secret);

		// Define claims
		Map<String, Object> claimsMap = new HashMap<>();
		claimsMap.put("name", "krishna");
		claimsMap.put("doman", "HR");

		// Define token creation and expiry times
		Date tokenCreatedTime = new Date();
		LocalDateTime localDateTime = LocalDateTime.ofInstant(tokenCreatedTime.toInstant(), ZoneId.systemDefault())
				.plusHours(8);
		Date tokenExpiryTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

		// Generate the jwt token
		String token = JWT.create().withIssuer("auth0").withIssuedAt(tokenCreatedTime).withExpiresAt(tokenExpiryTime)
				.withPayload(claimsMap).sign(algorithmHS);

		System.out.println("Generated token : " + token);

		// Verify the jwt token
		try {
			JWTVerifier verifier = JWT.require(algorithmHS).build();
			DecodedJWT jwt = verifier.verify(token);

			String payload = jwt.getPayload();
			Base64.Decoder base64Decoder = Base64.getDecoder();
			String tokenPayload = new String(base64Decoder.decode(payload));

			System.out.println(tokenPayload);

		} catch (JWTVerificationException exception) {
			// Invalid signature/claims
			exception.printStackTrace();
		}
	}
}

 

Sample Output

Generated token : eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMCIsIm5hbWUiOiJrcmlzaG5hIiwiZG9tYW4iOiJIUiIsImV4cCI6MTYyMjAzODM1NSwiaWF0IjoxNjIyMDA5NTU1fQ.clhaxkyuEK33jgak7dIWFi4Q_II2diAh_IhDF32mtNM
{"iss":"auth0","name":"krishna","doman":"HR","exp":1622038355,"iat":1622009555}

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment