Search

Suggested keywords:
  • Java
  • Docker
  • Git
  • React
  • NextJs
  • Spring boot
  • Laravel

Manage JWT Token using Auth0 java-jwt library

  • Share this:

post-title

In this article, we will learn how to create, validate JWT token using Auth0 java-jwt library.

Json Web Tokens (JWT)

JWT is an industry standary way to securely communicate between two parties. It is usually used in REST API where the client provides JWT token to securely access the API. It is a Base64 encoded string and it is usually used in stateless communication. Both party has to use the same encryption key. JWT token itself will contain the user context and validity period of the token. The other party should not accept the request if the token is expired.

It consists of 3 parts, Header, Payload and Signature.

Header

It has information of the algorithm used.

{
  "alg": "HS256",
  "typ": "JWT"
}

 

Payload

In JWT token, we can store custom payload or claims like subject, user_id, email_id, role etc. This will help both the parties to understand the context of the user. 

{
  "sub": "blackslate",
  "name": "Rahul",
   "userId": 1010101,
   "exp": 1543463453
 }

 

Signature

It is the hash value of the header and payload. Sender will sign it using its key and receiver will validate whether the content is tampered in transit.

Below is the sample JWT Token

eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJCbGFja3NsYXRlIiwiaXNzIjoiQmxhY2tzbGF0ZSIsIk5hbWUiOiJSYWh1bCIsIlJvbGUiOiJBZG1pbiIsIlVzZXJJZCI6IjEwMTAxMDEiLCJleHAiOjE3MTA1MTA3MzV9.WdrrE6fPzcto6yXf5CK-l0YD7ubqcKcXktiXjvopOZdfYmMm_f8jPwM1s8beS5N_ohIZP6WJ15rEUZQTf1KdqA

Dependency

Include the below dependency in your pom.xml

<dependency>
   	<groupId>com.auth0</groupId>
       <artifactId>java-jwt</artifactId>
       <version>4.4.0</version>
 </dependency>

 

Generate JWT Token

Before generating token, we need to first generate secure key which will be a random string. This key will be used to create and validate the token. 

static final String SECRET_KEY = "your-secret-key";

 

Let's create a token using HMAC512 algorithm and with validity of an hour.

public static String generateToken() {
		
		Algorithm algorithm = Algorithm.HMAC512(SECRET_KEY);

        //Add one hour
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.HOUR,  1);
		
		String token = JWT.create()
						  	 .withSubject("Blackslate")
						  	 .withIssuer("Blackslate")
							 .withClaim("Name", "Rahul")
							 .withClaim("Role", "Admin")
							 .withClaim("UserId", "1010101")
							 .withExpiresAt(cal.getTime())
							 .sign(algorithm);
		
		System.out.println(token);
		
		return token;
	}

In the code, we have used HMAC512 algorithm and set an validity for an hour. We have set various claims as part of the token. This claims can be decoded once verified.

The library supports various algorithm like ECDSA, RSA with varing key length. Based on the algorithm, we need to use the secure key with appropriate size.

 

Verify the token

Verify the token using the same algorithm and secure key.

public static void verifyToken(String token) {
		
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.HOUR,  -1);
		
		Algorithm algorithm = Algorithm.HMAC512(SECRET_KEY);

		JWTVerifier verifier = JWT.require(algorithm)
								 .acceptExpiresAt(120)
								 .build();
		
		try {
			DecodedJWT decodedJwt = verifier.verify(token);
			System.out.println(decodedJwt.getClaim("Name").asString());
		}
		catch(Exception exp) {
			System.out.println(exp.getMessage());
		}
			
	}

If the token is used beyond the expiration, exception will be thrown. We can also set some leeway where eventhough the token is expired, the token will be valid for the leeway period. In the code, the leeway is set to 120 seconds. This will be helpful, when both parties are in different timezone.

 

Decode the token

Let's decode the token and see its content. 

public static void decodeToken(String token) {
		
	String toks[] = token.split("\\.");
	for(int i=0; i < toks.length - 1; i++) {
		System.out.println(new String(Base64.getDecoder().decode(toks[i])));
	}	
}

 

The code will print below output header and payload. The third part is signature and it will be in binary.

{"alg":"HS512","typ":"JWT"}
{"sub":"Blackslate","iss":"Blackslate","Name":"Rahul","Role":"Admin","UserId":"1010101","exp":1710510735}

 

Source code available in Github.

Conclusion

In stateless communication where there is no session being maintained, JWT helps to authenticate and understand the user context.

 

Editorial Team

About author
This article is published by our editorial team.