Wednesday, 26 May 2021

Java: Generate jwt token using public, private key

Step 1: Get public and private key pair.

String algorithm = "RSA";
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);

KeyPair keyPair = keyPairGenerator.generateKeyPair();

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

Step 2: Get an instance of Algorithm using public, private key pair

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


Step 3: Define claims

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


Step 4: 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());


Step 5: Generate the jwt token

String token = JWT.create().withIssuer("auth0").withIssuedAt(tokenCreatedTime).withExpiresAt(tokenExpiryTime).withPayload(claimsMap).sign(algorithmRSA);


Find the below working application.

 

TokenGenerationUsingPublicPrivateKey.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.Date;
import java.util.HashMap;
import java.util.Map;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

public class TokenGenerationUsingPublicPrivateKey {

	public static void main(String args[]) throws NoSuchAlgorithmException {
		// Get public and private key pair
		String algorithm = "RSA";
		KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);

		KeyPair keyPair = keyPairGenerator.generateKeyPair();

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

		// Get an instance of Algorithm using public, private key pair
		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);

	}

}


Output

Token generated successfully : eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzUxMiJ9.eyJwZXJtaXNzaW9ucyI6WyJlZGl0b3IiLCJub3RpZmllciJdLCJpc3MiOiJhdXRoMCIsIm5hbWUiOiJrcmlzaG5hIiwiZG9tYW4iOiJIUiIsImV4cCI6MTYyMjA1ODgwMSwiaWF0IjoxNjIyMDMwMDAxfQ.m-RPUuvBJ1-XpkKlghHZ5lDJdUbvG04IWEN_8DJuZOKyxe3VvoCeHVIZTNGJrmeNRy1SjNooL4j0KvymFcRhTQk29vPr5LGT_bIfkepUgXtY6Ridl5OSWe_xBSe_SYhyYRe4Ip5qYHrXffxxD8NkGSBkaCDPBGFoDcnf4xKcyMk7wWn_uYouq39gVadDUeZmv4lBh8Krk9zRe8y_AD4AykcDMAABr51jifMZvrViepbVbmLSmtNB2ad6dgNDp9aLQoFh0IGLpTV48eKOOQ9KqdaS_Cty0BvMJKcCwMP4eJZrWmgY79j8fbXenunXjqQMgeSqW5ubG8eLmyncPNa71A


Decoded token information.

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment