Last Updated On
In this tutorial, we’ll learn how to create a JWT using the Auth0 JWT Java Library.
Table of Contents
- What is JWT Token?
- What is the JSON Web Token structure?
- Why Use JWT in Java Applications?
- Implementation
What is JWT Token?
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.
What is the JSON Web Token structure?
JSON Web Tokens consist of three parts separated by dots (.), which are:
- Header: Contains metadata about the token, such as the algorithm used.
{
"typ":"JWT",
"alg":"HS256"
}
- Payload: Contains claims, like subject, issuer, expiration, etc.
{
"iss": "QA_Automation",
"sub": "QA_Automation Details",
"userId": "9821",
"roles": "ROLE_ADMIN",
"scope": "read write",
"iat": 1680000000,
"exp": 1680000100,
"jti": "uuid-guid",
"nbf": 1680000001
}
- Signature: A cryptographic hash used to verify the token’s integrity.
HASHINGALGO( base64UrlEncode(header) + “.” + base64UrlEncode(payload),secret)
Why Use JWT in Java Applications?
1. Stateless Authentication: JWTs allow for stateless authentication, meaning the server doesn’t need to store user session information. This scalability and reduced server-side storage make JWTs advantageous for distributed systems.
2. Performance: Since JWTs are stateless, server-side lookup is eliminated. It Reduces server load and Improves response times for authenticated requests.
3. Interoperability: JWTs are designed to work across different technologies and systems. This interoperability is particularly useful in microservices architectures, where services may be implemented in different languages.
4. Cross-Domain Authentication: JWTs work well for Single Sign-On (SSO) and cross-domain authentication since they are independent of the application’s storage mechanisms.Users can log in once and access multiple applications without repeatedly authenticating.
5. Secure Data Transfer: The use of signatures in JWTs ensures that the data has not been tampered with during transmission. This provides a level of security when exchanging information between the client and server. Ensures token integrity with algorithms like HS256 (HMAC) or RS256 (RSA).
6. Expiration and Revocation: JWTs include an exp (expiration) claim and can include a revocation mechanism via blacklists. Tokens expire automatically after a set time.
7. Flexibility with Custom Claims: JWT allows adding custom claims like user roles, permissions, or metadata. Tailor the token to your application’s needs.
Add the java-jwt dependency to the project:
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.4.0</version>
</dependency>
Implementation
1. Create an instance of the Algorithm class. In this tutorial, we’ll use the HMAC256 algorithm to sign our JWT:
Algorithm algorithm = Algorithm.HMAC256("qa-automation-expert-details");
2. To create a JWT, we use the JWT.create() method. The method returns an instance of the JWTCreator.Builder class. We will use this Builder class to build the JWT token by signing the claims using the Algorithm instance:
Explanation of Claims and Methods:
- withIssuer(“QA_Automation”): Adds the iss (issuer) claim, identifying the source of the token.
- withSubject(“QA_Automation Details”): Adds the sub (subject) claim, describing the token’s purpose or context (e.g., user or system identity).
.withIssuer("QA_Automation")
.withSubject("QA_Automation Details")
Custom Claims:
- withClaim(“userId”, “9821”): Adds a custom userId claim to identify the user.
- withClaim(“roles”, “ROLE_ADMIN”): Adds a custom roles claim, defining user roles (e.g., ROLE_ADMIN).
- withClaim(“scope”, “read write”): Adds a custom scope claim, specifying allowed actions.
.withClaim("userId", "9821")
.withClaim("roles", "ROLE_ADMIN")
.withClaim("scope", "read write")
Standard Claims:
- withIssuedAt(new Date()): Sets the iat (issued at) claim to the current timestamp, indicating when the token was created.
- withExpiresAt(new Date(System.currentTimeMillis() + 10000L)): Sets the exp (expiration) claim to 10 seconds from the current time. After this, the token will no longer be valid.
- withJWTId(UUID.randomUUID().toString()): Adds a unique identifier (jti claim) for the token using a random UUID.
- withNotBefore(new Date(System.currentTimeMillis() + 100L)): Adds the nbf (not before) claim, setting the token to be valid 100 milliseconds in the future.
.withIssuedAt(new Date())
.withExpiresAt(new Date(System.currentTimeMillis() + 10000L))
.withJWTId(UUID.randomUUID().toString())
.withNotBefore(new Date(System.currentTimeMillis() + 100L))
sign(algorithm)
Signs the JWT using the specified algorithm (HMAC256 with the given secret key). The output is the final Base64Url-encoded JWT.
.sign(algorithm);
Below is the complete code to create a JWT Token.
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.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;
import java.util.UUID;
public class JWTTokenGenerator {
public static void main(String[] args) {
Algorithm algorithm = Algorithm.HMAC256("qa-automation-expert-details");
String jwtToken = JWT.create()
.withIssuer("QA_Automation")
.withSubject("QA_Automation Details")
.withClaim("userId", "9821")
.withClaim("roles", "ROLE_ADMIN")
.withClaim("scope", "read write")
.withIssuedAt(new Date())
.withExpiresAt(new Date(System.currentTimeMillis() + 10000L))
.withJWTId(UUID.randomUUID()
.toString())
.withNotBefore(new Date(System.currentTimeMillis() + 100L))
.sign(algorithm);
System.out.println("jwtToken :" + jwtToken);
}
}
The output of the above program is

Points to Consider:-
- Expiration: Tokens are set to expire (exp) after 10 seconds. This prevents misuse over time.
- Not Before: The nbf claim ensures the token is not valid until 100 milliseconds after creation.
- Claims: Custom claims like userId, roles, and scope allow encoding specific information for the application.
- JWT ID: The jti claim ensures token uniqueness.
That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!