Showing posts with label jwt. Show all posts
Showing posts with label jwt. Show all posts

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

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

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

JWT: Verify the token using static secret

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


 


Previous                                                    Next                                                    Home

JWT: Create a jwt token using static secret

In this post, I am going to explain how to create a new JWT token and sign it using static secret.

 

Step 1: Get an instance of signing algorithm using static secret.

String secret = "secret123";
Algorithm algorithmHS = Algorithm.HMAC256(secret);

Step 2: Define claims.

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


Step 3: 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 4: Generate jwt token.

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


Find the below working application.

 

TokenGenerationUsingStaticSecret.java

package com.sampple.app.examples;

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 TokenGenerationUsingStaticSecret {
	public static void main(String args[]) {

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

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

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


Output

Token generated successfully : eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwZXJtaXNzaW9ucyI6WyJlZGl0b3IiLCJub3RpZmllciJdLCJpc3MiOiJhdXRoMCIsIm5hbWUiOiJrcmlzaG5hIiwiZG9tYW4iOiJIUiIsImV4cCI6MTYyMjAzNTkyNywiaWF0IjoxNjIyMDA3MTI3fQ.9cimobXGLxSublYwNWRoKQjOr4Bo65sBhovhCoUD6qM


Token and decoded information


 

Previous                                                    Next                                                    Home