JSON Web Token in Java using Auth0 Java JWT Library

Introduction

In this Java tutorial, we learn how to work with JSON Web Token (JWT) in Java application using the Auth0’s Java JWT library.

How to add Java JWT Library to your Java project

To use the Java JWT library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'com.auth0:java-jwt:3.14.0'

To use the Java JWT library in the Maven build project, add the following dependency into the pom.xml file.

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

To have more information about the Java JWT library you can visit the library home page at github.com/auth0/java-jwt

How to generate a new JSON web token

In the following example, we generate a new JSON web token with 2 claim values username and role.

GenerateJWTExample.java

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

public class GenerateJWTExample {
    public static void main(String... args) {
        String secret = "123@abc";
        Algorithm algorithm = Algorithm.HMAC512(secret);

        String generatedToken = JWT.create()
                .withIssuer("Simple Solution")
                .withClaim("username", "TestUser")
                .withClaim("role", "User")
                .sign(algorithm);

        System.out.println(generatedToken);
    }
}
The output is:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJyb2xlIjoiVXNlciIsImlzcyI6IlNpbXBsZSBTb2x1dGlvbiIsInVzZXJuYW1lIjoiVGVzdFVzZXIifQ.jQUKIOxN0KGbIGJx8SU3WfSVPNASOnRtt3DcoMVBeThcWGzEBAnwlHHYRvbzuas-sOeWSvOwrnsvpQ5tywAfWA

In the following Java program, we learn to generate a JWT token that will expire in 1 minute.

GenerateJWTWithExpireExample.java

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

import java.util.Date;

public class GenerateJWTWithExpireExample {
    public static void main(String... args) {
        String secret = "123@abc";
        Algorithm algorithm = Algorithm.HMAC512(secret);
        long expireTime = (new Date().getTime()) + 60000; // 60000 milliseconds = 60 seconds = 1 minute
        Date expireDate = new Date(expireTime);

        String generatedToken = JWT.create()
                .withIssuer("Simple Solution")
                .withClaim("username", "TestUser")
                .withClaim("role", "User")
                .withExpiresAt(expireDate)
                .sign(algorithm);

        System.out.println(generatedToken);
    }
}
The output is:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJyb2xlIjoiVXNlciIsImlzcyI6IlNpbXBsZSBTb2x1dGlvbiIsImV4cCI6MTYxNjA4MDAzOCwidXNlcm5hbWUiOiJUZXN0VXNlciJ9.S96EHjYKfWfB4TEXqUBfIJVOEBkOWD9wd37OhIJ4TcxTND9Igni0pHiMB-i3efxSaiiQEGvi-pMrwGKISue1MA

How to verify the a JSON web token

Verify the token without expiration date time.

VerifyJWTExample.java

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

public class VerifyJWTExample {
    public static void main(String... args) {
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJyb2xlIjoiVXNlciIsImlzcyI6IlNpbXBsZSBTb2x1dGlvbiIsInVzZXJuYW1lIjoiVGVzdFVzZXIifQ.jQUKIOxN0KGbIGJx8SU3WfSVPNASOnRtt3DcoMVBeThcWGzEBAnwlHHYRvbzuas-sOeWSvOwrnsvpQ5tywAfWA";
        String secret = "123@abc";
        Algorithm algorithm = Algorithm.HMAC512(secret);

        try {
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("Simple Solution")
                    .build();

            DecodedJWT decodedJWT = verifier.verify(token);

            System.out.println("Verify JWT token success.");
            System.out.println("Claims: " + decodedJWT.getClaims());
        } catch (JWTVerificationException ex) {
            System.out.println("Verify JWT token fail: " + ex.getMessage());
        }
    }
}
The output is:
Verify JWT token success.
Claims: {iss="Simple Solution", role="User", username="TestUser"}

Verify the token with expiration date time.

VerifyJWTWithExpireExample.java

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

public class VerifyJWTWithExpireExample {
    public static void main(String... args) {
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJyb2xlIjoiVXNlciIsImlzcyI6IlNpbXBsZSBTb2x1dGlvbiIsImV4cCI6MTYxNjA4MDEyMCwidXNlcm5hbWUiOiJUZXN0VXNlciJ9.bw87xWcl23Nefzeilnww84kUxvz3Yal90Va6DQogsRhVWvZe_TvmzFkib4ecIKbScMCQnR4a-w3JfaKBw7btNw";
        String secret = "123@abc";
        Algorithm algorithm = Algorithm.HMAC512(secret);

        try {
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("Simple Solution")
                    .acceptExpiresAt(60) // 60 seconds = 1 minute
                    .build();

            DecodedJWT decodedJWT = verifier.verify(token);

            System.out.println("Verify JWT token success.");
            System.out.println(decodedJWT.getClaims());
        } catch (JWTVerificationException ex) {
            System.out.println("Verify JWT token fail: " + ex.getMessage());
        }
    }
}
The output is:
Verify JWT token success.
{iss="Simple Solution", role="User", exp=1616080120, username="TestUser"}

How to decode a given JSON web token

In the following Java program, we learn how to decode a given JSON web token and show its issuer and claims data.

DecodeJWTExample.java

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;

public class DecodeJWTExample {
    public static void main(String... args) {
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJyb2xlIjoiVXNlciIsImlzcyI6IlNpbXBsZSBTb2x1dGlvbiIsInVzZXJuYW1lIjoiVGVzdFVzZXIifQ.jQUKIOxN0KGbIGJx8SU3WfSVPNASOnRtt3DcoMVBeThcWGzEBAnwlHHYRvbzuas-sOeWSvOwrnsvpQ5tywAfWA";

        DecodedJWT decodedJWT = JWT.decode(token);

        System.out.println("Issuer: " + decodedJWT.getIssuer());
        System.out.println("Claims: " + decodedJWT.getClaims());
    }
}
The output is:
Issuer: Simple Solution
Claims: {iss="Simple Solution", role="User", username="TestUser"}

Implement a reusable JWTService class

At this step, we learn how to implement a reusable class to generate, verify and decode JSON web tokens that can reuse for your Java project.

JWTService.java

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

public class JWTService {

    private long DEFAULT_EXPIRE_IN_SECONDS = 60;
    
    private String secret = "123@abc";

    private Algorithm algorithm = Algorithm.HMAC256(secret);

    public String generateJWTToken(String username, String role) {
        long now = new Date().getTime();
        long expireTime = now + (DEFAULT_EXPIRE_IN_SECONDS * 1000);
        Date expireDate = new Date(expireTime);

        String jwtToken = JWT.create()
                .withIssuer("Simple Solution")
                .withClaim("username", username)
                .withClaim("role", role)
                .withExpiresAt(expireDate)
                .sign(algorithm);

        return jwtToken;
    }

    public boolean verifyJWTToken(String token) {
        try {
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("Simple Solution")
                    .acceptExpiresAt(DEFAULT_EXPIRE_IN_SECONDS)
                    .build();

            verifier.verify(token);
            return true;
        } catch (JWTVerificationException ex) {
            return false;
        }
    }

    public String getClaimFromToken(String token, String claimKey) {
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getClaims().get(claimKey).toString();
    }
}

Example program how to use JWTService class.

JWTExamples.java

public class JWTExamples {
    public static void main(String[] args) {
        JWTService jwtService = new JWTService();
        String token = jwtService.generateJWTToken("TestUser", "User");
        boolean result = jwtService.verifyJWTToken(token);

        System.out.println("Generated Token: " + token);
        System.out.println("Verify Result: " + result);
        System.out.println("Token Claim, username: " + jwtService.getClaimFromToken(token, "username"));
        System.out.println("Token Claim, role: " + jwtService.getClaimFromToken(token, "role"));
    }
}
The output is:
Generated Token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoiVXNlciIsImlzcyI6IlNpbXBsZSBTb2x1dGlvbiIsImV4cCI6MTYxNjA4MDM0MywidXNlcm5hbWUiOiJUZXN0VXNlciJ9.4NLv-75XG-uyz-3YjnuRau7aKOOUagJ9szdWDR-OR7k
Verify Result: true
Token Claim, username: "TestUser"
Token Claim, role: "User"

Conclusion

In this Java JSON web token tutorial, we have learned how to use the Java JWT library to generate a new token, verify and decode a given token. We also implement a reusable Java class to reuse for different Java projects.

Happy Coding 😊