JWT generation creates a secure token to identify users safely. It helps servers know who is making requests without asking for passwords every time.
JWT generation in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Spring Boot
String jwt = Jwts.builder()
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + expirationTime))
.signWith(Keys.hmacShaKeyFor(secretKey.getBytes()), SignatureAlgorithm.HS256)
.compact();setSubject sets the user identity inside the token.
signWith uses a secret key to make the token secure and hard to fake.
Examples
Spring Boot
String token = Jwts.builder()
.setSubject("user123")
.signWith(Keys.hmacShaKeyFor("mySecretKeymySecretKeymySecretKeymySecretKey".getBytes()), SignatureAlgorithm.HS256)
.compact();Spring Boot
String token = Jwts.builder()
.setSubject("user123")
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 3600000))
.signWith(Keys.hmacShaKeyFor("mySecretKeymySecretKeymySecretKeymySecretKey".getBytes()), SignatureAlgorithm.HS256)
.compact();Sample Program
This Spring Boot compatible Java class creates a JWT token for a username. It sets the token to expire in 1 hour and signs it with a secret key. The main method prints the token.
Spring Boot
package com.example.jwt; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.security.Keys; import java.util.Date; import javax.crypto.SecretKey; public class JwtGenerator { private static final String SECRET_KEY_STRING = "mySecretKeymySecretKeymySecretKeymySecretKey"; private static final SecretKey SECRET_KEY = Keys.hmacShaKeyFor(SECRET_KEY_STRING.getBytes()); private static final long EXPIRATION_TIME = 3600000; // 1 hour in milliseconds public static String generateToken(String username) { return Jwts.builder() .setSubject(username) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) .signWith(SECRET_KEY, SignatureAlgorithm.HS256) .compact(); } public static void main(String[] args) { String token = generateToken("user123"); System.out.println("Generated JWT Token:"); System.out.println(token); } }
Important Notes
Keep your secret key safe and never share it publicly.
Tokens expire to keep security strong; always set expiration.
Use libraries like jjwt for easy JWT handling in Spring Boot.
Summary
JWT tokens securely identify users without storing sessions.
Use a secret key to sign tokens and set expiration times.
Spring Boot apps can generate JWTs using the jjwt library easily.
Practice
1. What is the main purpose of generating a JWT (JSON Web Token) in a Spring Boot application?
easy
Solution
Step 1: Understand JWT purpose
JWTs are used to securely identify users by encoding user info and signing it.Step 2: Compare options
Only To securely identify users without storing session data on the server describes JWT's role in stateless authentication without server sessions.Final Answer:
To securely identify users without storing session data on the server -> Option AQuick Check:
JWT purpose = secure user identity without sessions [OK]
Hint: JWTs identify users without server sessions [OK]
Common Mistakes:
- Confusing JWT with session storage
- Thinking JWT stores passwords
- Assuming JWT creates web pages
2. Which of the following code snippets correctly initializes a JWT builder using the jjwt library in Spring Boot?
easy
Solution
Step 1: Recall jjwt syntax
The correct method chain starts with Jwts.builder(), uses setSubject(), signWith(), then compact().Step 2: Check each option
Jwts.builder().setSubject("user").signWith(secretKey).compact(); matches the correct method names and order. Others use incorrect method names or chaining.Final Answer:
Jwts.builder().setSubject("user").signWith(secretKey).compact(); -> Option DQuick Check:
Correct jjwt builder syntax = Jwts.builder().setSubject("user").signWith(secretKey).compact(); [OK]
Hint: Use Jwts.builder(), setSubject(), signWith(), compact() [OK]
Common Mistakes:
- Using incorrect method names like sign() instead of signWith()
- Missing Jwts.builder() start
- Using create() or build() instead of compact()
3. Given the following code snippet, what will be the output type of the
token variable?String token = Jwts.builder()
.setSubject("user123")
.signWith(secretKey)
.compact();medium
Solution
Step 1: Understand compact() output
The compact() method returns the JWT as a compact URL-safe string.Step 2: Analyze code snippet
The code builds a JWT with subject and signs it, then calls compact(), so token is a String.Final Answer:
A signed JWT string token -> Option BQuick Check:
compact() returns String token [OK]
Hint: compact() returns JWT as a string [OK]
Common Mistakes:
- Expecting a JSON object instead of string
- Thinking output is byte array
- Assuming code throws exception without error
4. Identify the error in this JWT generation code snippet:
String token = Jwts.builder()
.setSubject("user")
.signWith("mySecretKey")
.compact();medium
Solution
Step 1: Check signWith() parameter type
signWith() expects a java.security.Key or SecretKey, not a plain String.Step 2: Verify other methods
setSubject() accepts String, compact() is correctly called last, and Jwts.builder() is valid.Final Answer:
signWith() requires a Key object, not a String -> Option CQuick Check:
signWith() needs Key, not String [OK]
Hint: Use Key object with signWith(), not plain String [OK]
Common Mistakes:
- Passing String directly to signWith()
- Calling compact() too early
- Misunderstanding setSubject() input
5. You want to generate a JWT in Spring Boot that expires in 10 minutes. Which code snippet correctly sets the expiration time using jjwt?
hard
Solution
Step 1: Understand expiration setting in jjwt
setExpiration() expects a Date object representing the expiration time.Step 2: Calculate expiration time
Use current time plus 600000 milliseconds (10 minutes) to set expiration correctly.Step 3: Check options
Only Jwts.builder().setSubject("user").setExpiration(new Date(System.currentTimeMillis() + 600000)).signWith(secretKey).compact(); correctly uses setExpiration() with new Date(System.currentTimeMillis() + 600000).Final Answer:
Jwts.builder().setSubject("user").setExpiration(new Date(System.currentTimeMillis() + 600000)).signWith(secretKey).compact(); -> Option AQuick Check:
setExpiration(Date) with currentTime + 10min = Jwts.builder().setSubject("user").setExpiration(new Date(System.currentTimeMillis() + 600000)).signWith(secretKey).compact(); [OK]
Hint: Use setExpiration(new Date(System.currentTimeMillis() + millis)) [OK]
Common Mistakes:
- Using setExpiry() or setExpiresAt() which don't exist
- Passing milliseconds directly instead of Date
- Setting expiration to a fixed past date
