Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Authentication with JWT token
📖 Scenario: You are building a simple Spring Boot backend for a web app that needs secure user login. You will create a JWT token authentication system to protect user data.
🎯 Goal: Build a Spring Boot project that creates a JWT token after user login and validates it for protected routes.
📋 What You'll Learn
Create a user data structure with username and password
Add a secret key configuration for JWT token signing
Implement JWT token creation logic after successful login
Add JWT token validation filter to secure API endpoints
💡 Why This Matters
🌍 Real World
JWT tokens are widely used to secure APIs by verifying user identity without storing session data on the server.
💼 Career
Understanding JWT authentication is essential for backend developers working on secure web applications and REST APIs.
Progress0 / 4 steps
1
Create User Data Structure
Create a Java record called User with two fields: username of type String and password of type String.
Spring Boot
Hint
Use Java 17+ record syntax to create a simple immutable data class.
2
Add JWT Secret Key Configuration
Create a String variable called jwtSecret and set it to the value "mySecretKey12345" inside a class called JwtConfig.
Spring Boot
Hint
Use a public static final String for the secret key inside JwtConfig class.
3
Implement JWT Token Creation Logic
Inside a class called JwtUtil, write a method public static String generateToken(String username) that returns a JWT token string. Use io.jsonwebtoken.Jwts builder with setSubject(username), signWith using JwtConfig.jwtSecret and compact() to create the token.
Spring Boot
Hint
Use Jwts.builder() to create the token with subject and sign it with HS256 algorithm and the secret key.
4
Add JWT Token Validation Filter
Create a class JwtFilter that extends OncePerRequestFilter. Override doFilterInternal method to extract the JWT token from the Authorization header, validate it using Jwts.parser().setSigningKey(JwtConfig.jwtSecret).parseClaimsJws(token), and then call filterChain.doFilter(request, response).
Spring Boot
Hint
Extract the token from Authorization header, validate it with Jwts.parser(), and call filterChain.doFilter() if valid.
Practice
(1/5)
1. What is the main purpose of using a JWT token in Spring Boot authentication?
easy
A. To store user passwords in the database
B. To securely transmit user identity without sending passwords every time
C. To encrypt the entire application data
D. To replace the need for HTTPS
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 B
Quick 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
A. String token = request.getParameter("Authorization");
B. String token = request.getCookie("jwt");
C. String token = request.getBody();
D. String token = request.getHeader("Authorization").substring(7);
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 D
Quick 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?
A. Incorrect method to set signing key in new jjwt versions
B. Missing call to build() before compact()
C. Username should not be set as subject
D. Missing token expiration setting
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 A
Quick 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
A. Set token expiration to 15 minutes and issue a new token with updated expiration on each valid request
B. Set token expiration to 15 minutes and never refresh tokens; force user to login again after expiry
C. Set token expiration to 1 hour and refresh tokens only when user logs out
D. Do not set expiration and refresh tokens every time to keep user logged in indefinitely
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 A
Quick Check:
Short expiration + refresh token = secure session [OK]
Hint: Short expiration plus refresh token on requests [OK]