JWT tokens help keep users logged in safely without saving passwords everywhere. They prove who you are in a simple way.
Authentication with JWT token 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 token = Jwts.builder()
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + expirationTime))
.signWith(SignatureAlgorithm.HS512, secretKey)
.compact();This code creates a JWT token with a username, issue time, expiration, and a secret key.
Use a strong secret key and keep it safe to protect your tokens.
Examples
Spring Boot
String token = Jwts.builder()
.setSubject("user123")
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 1 day
.signWith(SignatureAlgorithm.HS256, "mySecretKey")
.compact();Spring Boot
Claims claims = Jwts.parser()
.setSigningKey("mySecretKey")
.parseClaimsJws(token)
.getBody();
String username = claims.getSubject();Sample Program
This program creates a JWT token for user "alice" valid for 1 hour, then reads the username back from the token.
Spring Boot
package com.example.demo; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.Claims; import java.util.Date; public class JwtExample { private static final String SECRET_KEY = "mySecretKey12345"; private static final long EXPIRATION_TIME = 3600000; // 1 hour in ms public static String generateToken(String username) { return Jwts.builder() .setSubject(username) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) .signWith(SignatureAlgorithm.HS512, SECRET_KEY) .compact(); } public static String validateTokenAndGetUsername(String token) { Claims claims = Jwts.parser() .setSigningKey(SECRET_KEY) .parseClaimsJws(token) .getBody(); return claims.getSubject(); } public static void main(String[] args) { String token = generateToken("alice"); System.out.println("Generated Token: " + token); String username = validateTokenAndGetUsername(token); System.out.println("Username from token: " + username); } }
Important Notes
Always keep your secret key private and never share it.
Tokens have expiration times to limit how long they are valid.
Use HTTPS to protect tokens when sent over the internet.
Summary
JWT tokens let you prove who you are without sending passwords repeatedly.
Spring Boot uses libraries like jjwt to create and check tokens easily.
Keep tokens safe and use expiration to improve security.
Practice
1. What is the main purpose of using a JWT token in Spring Boot authentication?
easy
Solution
Step 1: Understand JWT token role
JWT tokens are used to prove user identity securely without resending passwords.Step 2: Compare options with JWT purpose
Only To securely transmit user identity without sending passwords every time correctly describes this purpose; others are unrelated or incorrect.Final Answer:
To securely transmit user identity without sending passwords every time -> Option BQuick Check:
JWT token purpose = secure identity proof [OK]
Hint: JWT tokens prove identity without passwords [OK]
Common Mistakes:
- Thinking JWT stores passwords
- Confusing JWT with data encryption
- Assuming JWT replaces HTTPS
2. Which of the following is the correct way to extract the JWT token from an HTTP request header in Spring Boot?
easy
Solution
Step 1: Identify JWT token location in HTTP request
JWT tokens are usually sent in the Authorization header with prefix "Bearer ".Step 2: Extract token correctly
String token = request.getHeader("Authorization").substring(7); extracts the header and removes the "Bearer " prefix (7 characters), which is correct.Final Answer:
String token = request.getHeader("Authorization").substring(7); -> Option DQuick Check:
Extract JWT from Authorization header [OK]
Hint: JWT is in Authorization header with 'Bearer ' prefix [OK]
Common Mistakes:
- Using request parameters instead of headers
- Trying to get token from request body
- Assuming token is in cookies by default
3. Given this Spring Boot JWT validation snippet, what will be the output if the token is expired?
try {
Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token);
System.out.println("Token is valid");
} catch (ExpiredJwtException e) {
System.out.println("Token expired");
} catch (JwtException e) {
System.out.println("Invalid token");
}medium
Solution
Step 1: Understand exception handling in JWT parsing
If the token is expired, the parser throws ExpiredJwtException, caught by the first catch block.Step 2: Identify printed output for expired token
The catch block prints "Token expired" when ExpiredJwtException occurs.Final Answer:
Token expired -> Option CQuick Check:
Expired token triggers ExpiredJwtException [OK]
Hint: ExpiredJwtException means token expired [OK]
Common Mistakes:
- Confusing expired token with invalid token
- Ignoring exception handling order
- Assuming no output on exceptions
4. Identify the error in this JWT token generation code snippet in Spring Boot:
String token = Jwts.builder() .setSubject(username) .signWith(SignatureAlgorithm.HS256, secretKey) .compact();
medium
Solution
Step 1: Check jjwt signing method usage
In recent jjwt versions, signWith requires a Key object, not just algorithm and string key.Step 2: Identify correct signing method
Using signWith(SignatureAlgorithm, String) is deprecated and causes errors; must use signWith(Key).Final Answer:
Incorrect method to set signing key in new jjwt versions -> Option AQuick Check:
Use Key object with signWith in jjwt [OK]
Hint: Use Key object, not algorithm + string, in signWith [OK]
Common Mistakes:
- Ignoring jjwt version changes
- Assuming string key is accepted directly
- Confusing expiration with signing errors
5. You want to implement JWT authentication in Spring Boot that automatically rejects tokens older than 15 minutes and refreshes tokens on each valid request. Which approach correctly combines expiration and refresh logic?
hard
Solution
Step 1: Understand token expiration and refresh needs
To reject tokens older than 15 minutes, set expiration to 15 minutes.Step 2: Implement refresh on each valid request
Issuing a new token with updated expiration on each valid request keeps user session active securely.Final Answer:
Set token expiration to 15 minutes and issue a new token with updated expiration on each valid request -> Option AQuick Check:
Short expiration + refresh token = secure session [OK]
Hint: Short expiration plus refresh token on requests [OK]
Common Mistakes:
- Not refreshing tokens causing forced logouts
- Setting too long expiration risking security
- Ignoring expiration causing infinite sessions
