Wednesday 26 May 2021

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

No comments:

Post a Comment