How to Generate JWT Token in Java

Generate JWT Token in Java

In this example program, We will show you how to generate JWT token in Java. This example program has been tested and shared in the same post.

Maven Dependency

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

Gradle Dependency

compile group: 'com.auth0', name: 'java-jwt', version: '3.3.0'

Example Program

package com.dineshkrish;

import java.io.UnsupportedEncodingException;

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

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class TokenUtil {

	public static String getToken(final String scretKey) {

		String token = null;

		try {

			Algorithm algorithm = Algorithm.HMAC256("scretKey");

			Builder builder = JWT.create();

			token = builder.sign(algorithm);

		} catch (IllegalArgumentException e) {

			System.out.println(e.getMessage());

		} catch (UnsupportedEncodingException e) {

			System.out.println(e.getMessage());
		}

		return token;
	}

	public static void main(String[] args) {

		String scretKey = "dk";

		String token = TokenUtil.getToken(scretKey);

		System.out.println("The Token is : " + token);

	}

}

Output

The Token is : eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.e30.8ncZMmAYXGQiCdPmvhDGI6YMUDVHkXYS8hT5-79PWcs

References

1. https://jwt.io/
2. https://tools.ietf.org/html/rfc7519
3. https://en.wikipedia.org/wiki/JSON_Web_Token

Hello, folks, I am a founder of dineshkrish.com. I love Java and Open source technologies, If you find my tutorials are useful, please consider making donations to these charities.