Wednesday 26 May 2021

Java: Verify the token using public and private key

 Below snippet is used to verify the jwt token using public, private key pair.

JWTVerifier verifier = JWT.require(algorithmRSA).build();
DecodedJWT jwt = verifier.verify(token);

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

Find the below working application.

 

JWTWithPublicPrivateKeyDemo.java

package com.sampple.app.examples;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
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 JWTWithPublicPrivateKeyDemo {

	public static void main(String args[]) throws NoSuchAlgorithmException {
		String algorithm = "RSA";
		KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);

		KeyPair keyPair = keyPairGenerator.generateKeyPair();

		RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

		Algorithm algorithmRSA = Algorithm.RSA512(rsaPublicKey, privateKey);

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

		// 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(algorithmRSA);

		System.out.println("Token generated successfully : " + token);

		// Verify the jwt token
		JWTVerifier verifier = JWT.require(algorithmRSA).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);

	}

}


Output

Token generated successfully : eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzUxMiJ9.eyJwZXJtaXNzaW9ucyI6WyJlZGl0b3IiLCJub3RpZmllciJdLCJpc3MiOiJhdXRoMCIsIm5hbWUiOiJrcmlzaG5hIiwiZG9tYW4iOiJIUiIsImV4cCI6MTYyMjA1OTU1OSwiaWF0IjoxNjIyMDMwNzU5fQ.lO3oOjeINKCis4vv-1OZPJgELtN_kSNvFTeDIumES13ZUMi5l3Cr2c9d0CnOkOw3OHzTXQxYC-RrYBCHe6xCrKzBTtMtrw_ndHdME9OJ3A12Ag_LE97CDQNKdrUNmNfEcn8kwwjlnb6ipv3mOa-u0KCrcdCJHNWAnMJk1O88MYU73rQOTI9iR0DrhytOKZdt7YX4Jx-t27VZM1E-rdmYx37aWt7T2hGBrKTCCS6ytGodndNCW965erz15MbtSEjlujYR_cxMObQuUvvmMxfijm04KTI3tTMoW5EKbwwiY23TbsipnDT5M4brHtWcNsuL0_B8UN-Hg2sWIvk9yYYbuA
{"permissions":["editor","notifier"],"iss":"auth0","name":"krishna","doman":"HR","exp":1622059559,"iat":1622030759}

 

Token with decoded information


 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment