Bird
Raised Fist0
Spring Bootframework~10 mins

Authentication with JWT token in Spring Boot - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

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
Concept Flow - Authentication with JWT token
User sends login request
Server verifies credentials
Generate JWT token
Send JWT token to user
User sends requests with JWT
Server validates JWT token
Allow access
This flow shows how a user logs in, receives a JWT token, and uses it for authenticated requests.
Execution Sample
Spring Boot
POST /login {username, password}
-> Server checks credentials
-> If valid, create JWT token
-> Return token to user
User sends request with Authorization: Bearer <token>
Server validates token and grants access
This code simulates login, token creation, and token validation for authentication.
Execution Table
StepActionInput/ConditionResultNext Step
1Receive login requestusername=alice, password=1234Credentials checked2
2Verify credentialsAre username and password correct?Yes3
3Generate JWT tokenUser info encoded in tokenToken created with expiry4
4Send token to userToken sent in responseUser receives token5
5User sends request with tokenAuthorization header with tokenServer extracts token6
6Validate tokenIs token signature valid and not expired?Yes7
7Grant accessToken validUser allowed to access resourceEnd
8If credentials invalidNoReject login with errorEnd
9If token invalidNoReject request with 401 UnauthorizedEnd
💡 Execution stops when user is granted access or denied due to invalid credentials or token.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 6Final
usernamenullalicealicealicealice
passwordnull1234123412341234
credentialsValidfalsetruetruetruetrue
jwtTokennullnulltokenStringtokenStringtokenString
tokenValidfalsefalsefalsetruetrue
Key Moments - 3 Insights
Why does the server reject access if the token is expired even if it was originally valid?
Because the execution_table row 6 shows token validation checks expiry and signature. Expired tokens fail validation and lead to rejection at step 9.
What happens if the user sends a request without a token?
The server cannot validate the token (step 6), so it treats it as invalid and denies access (step 9). This is implied by the token extraction and validation steps.
Why do we generate a token only after verifying credentials?
As shown in steps 2 and 3, token generation happens only if credentials are valid to ensure only authenticated users get tokens.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'credentialsValid' after step 2?
Atrue
Bfalse
Cnull
Dundefined
💡 Hint
Check variable_tracker column 'After Step 2' for 'credentialsValid'
At which step does the server send the JWT token to the user?
AStep 3
BStep 5
CStep 4
DStep 6
💡 Hint
Look at execution_table row describing 'Send token to user'
If the token is invalid, which step in the execution_table shows the server denying access?
AStep 7
BStep 9
CStep 8
DStep 6
💡 Hint
Check the rows where token validation fails and access is denied
Concept Snapshot
Authentication with JWT token in Spring Boot:
- User logs in with credentials
- Server verifies credentials
- If valid, server creates JWT token with user info
- Token sent to user for future requests
- User sends token in Authorization header
- Server validates token signature and expiry
- If valid, access granted; else denied
- Tokens allow stateless, secure authentication
Full Transcript
This visual execution shows how authentication with JWT token works in Spring Boot. First, the user sends a login request with username and password. The server checks if these credentials are correct. If they are, the server generates a JWT token that encodes user information and an expiry time. This token is sent back to the user. Later, when the user sends requests, they include this token in the Authorization header. The server extracts the token and validates its signature and expiry. If the token is valid, the server grants access to the requested resource. If the credentials or token are invalid, the server rejects the request. This process allows secure, stateless authentication without storing session data on the server.

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

  1. Step 1: Understand JWT token role

    JWT tokens are used to prove user identity securely without resending passwords.
  2. 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.
  3. Final Answer:

    To securely transmit user identity without sending passwords every time -> Option B
  4. 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

  1. Step 1: Identify JWT token location in HTTP request

    JWT tokens are usually sent in the Authorization header with prefix "Bearer ".
  2. 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.
  3. Final Answer:

    String token = request.getHeader("Authorization").substring(7); -> Option D
  4. 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?
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
A. Invalid token
B. Token is valid
C. Token expired
D. No output

Solution

  1. Step 1: Understand exception handling in JWT parsing

    If the token is expired, the parser throws ExpiredJwtException, caught by the first catch block.
  2. Step 2: Identify printed output for expired token

    The catch block prints "Token expired" when ExpiredJwtException occurs.
  3. Final Answer:

    Token expired -> Option C
  4. Quick 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
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

  1. Step 1: Check jjwt signing method usage

    In recent jjwt versions, signWith requires a Key object, not just algorithm and string key.
  2. Step 2: Identify correct signing method

    Using signWith(SignatureAlgorithm, String) is deprecated and causes errors; must use signWith(Key).
  3. Final Answer:

    Incorrect method to set signing key in new jjwt versions -> Option A
  4. 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

  1. Step 1: Understand token expiration and refresh needs

    To reject tokens older than 15 minutes, set expiration to 15 minutes.
  2. Step 2: Implement refresh on each valid request

    Issuing a new token with updated expiration on each valid request keeps user session active securely.
  3. Final Answer:

    Set token expiration to 15 minutes and issue a new token with updated expiration on each valid request -> Option A
  4. Quick 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