Add JWT library in pom.xml

    
<!-- pom.xml -->
        <!-- JWT Token Creation Library -->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.4.0</version>
        </dependency>


Create JWT Token

    
        public static String generateJWTToken() {
        String signatureSecret = "SECRET_VALUE_FOR_SIGNATURE";
        Algorithm algorithm = Algorithm.HMAC256(signatureSecret);

        Calendar c = Calendar.getInstance();
        Date currentDate = c.getTime();

        c.add(Calendar.HOUR, 24);
        Date expireDate = c.getTime();

        String jwtToken = JWT.create()
                .withIssuer("smoothprogramming")
                .withSubject("demo")
                .withAudience("techgeeks")
                .withIssuedAt(currentDate)
                .withExpiresAt(expireDate)
                .withClaim("Claim1", "Value1")
                .withClaim("Claim2", "Value2")
                .sign(algorithm);

        return jwtToken;
    }
    

Verify JWT Token

    
        public static void verifyJWTToken(String jwtToken) {
        String signatureSecret = "SECRET_VALUE_FOR_SIGNATURE";
        Algorithm algorithm = Algorithm.HMAC256(signatureSecret);

        JWTVerifier verifier = JWT.require(algorithm)
                .withIssuer("smoothprogramming")
                .withSubject("demo")
                .build();

        DecodedJWT decodedJWT = verifier.verify(jwtToken);
        System.out.println("Claim1 is "+ decodedJWT.getClaim("Claim1").asString());
        System.out.println("Claim2 is "+ decodedJWT.getClaim("Claim2").asString());
    }
    



Code

Find the code at Github Repo.

References:
https://jwt.io/