JWT (JSON Web Token) Java Example

JWT (JSON Web Token) Java Example | JWT (JSON Web Token) is an open-source service (API) that supports generating tokens based on client details and secretKey. It is token-based and stateless authentication (No HTTP session). Also see:- Stateful and Stateless Authentication

JWT Format:-

  • Header: JWT Specific information
  • Payload: Claims (ClientID, ClientName, ProviderName, Date, expiryDate, etc)
  • Signature: Base64Encode(Header) + Base64Encoder(payload) <- secretKey

Example token format:- header.payload.signature (aaaaaa.bbbbb.cccc)

Sample Encoded JWT:-
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Sample Decoded JWT:-

Header:-

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

Payload:-

{
  "id": "1234567890",
  "subject": "John Doe",
  "issuer": "KnowProgram",
  "issueDate": "<dateAndTime>",
  "expiryDate": "<dateAndTime>",
  "iat": 1516239022
}

Signature:-

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  <your-256-bit-secret>
) 

Process:-

  1. Generate Token Using JWT Java API
  2. Read and Validate the Token using JWT Java API

To implement this we have to use JJWT dependencies (Java JWT). Java JWT API is an open-source Java API.

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-api</artifactId>
    <version>0.11.5</version>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-impl</artifactId>
    <version>0.11.5</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if you prefer -->
    <version>0.11.5</version>
    <scope>runtime</scope>
</dependency>

Create a Simple Maven Project. Add the above dependency in <dependencies></dependencies>.

Claims – Read/Parse JWT Details by providing two inputs.

  1. Token
  2. Secret Key
import java.security.Key;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

public class JwtUtil {
    // Generate a secure random key
    Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);

    // generate token
    public String generateToken(String id, String subject) {
        return Jwts.builder()
        .setId(id).setSubject(subject)
        .setIssuer("KnowProgram")
        .setIssuedAt(new Date(System.currentTimeMillis()))
        .setExpiration(new Date(System.currentTimeMillis() + 
                TimeUnit.MINUTES.toMillis(10)))
        .signWith(key)
        .compact();
    }

    // get claims
    public Claims getClaims(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    public String getSubject(String token) {
        return getClaims(token).getSubject();
    }

    public boolean isValidToken(String token) {
        return getClaims(token)
                .getExpiration().after(
                        new Date(System.currentTimeMillis()
                 ));
    }
}
import io.jsonwebtoken.Claims;

public class Test {
    public static void main(String[] args) {
        JwtUtil jwtUtil = new JwtUtil();

        String token = jwtUtil.generateToken("AA885", "Jerry");
        System.out.println("Generated token: " + token);

        Claims claims = jwtUtil.getClaims(token);
        System.out.println();
        System.out.println(claims);
        System.out.println(claims.getSubject());
        System.out.println(claims.getId());
        System.out.println(claims.getIssuer());
        System.out.println(claims.getExpiration());
    }
}

Output:-

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *