Bird
Raised Fist0
Spring Bootframework~20 mins

Refresh token pattern in Spring Boot - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Refresh Token Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when a refresh token is expired in this Spring Boot code?
Consider this simplified Spring Boot controller method that handles refresh tokens. What will be the HTTP response status if the refresh token is expired?
Spring Boot
public ResponseEntity<?> refreshToken(@RequestBody TokenRefreshRequest request) {
    String requestRefreshToken = request.getRefreshToken();
    return refreshTokenService.findByToken(requestRefreshToken)
        .map(refreshTokenService::verifyExpiration)
        .map(RefreshToken::getUser)
        .map(user -> {
            String token = jwtUtils.generateTokenFromUsername(user.getUsername());
            return ResponseEntity.ok(new TokenRefreshResponse(token, requestRefreshToken));
        })
        .orElseThrow(() -> new TokenRefreshException(requestRefreshToken, "Refresh token is not in database!"));
}
AReturns HTTP 200 with a new access token
BReturns HTTP 500 Internal Server Error due to null pointer
CReturns HTTP 401 Unauthorized without a new token
DThrows TokenRefreshException leading to HTTP 403 Forbidden
Attempts:
2 left
💡 Hint
Look at what happens when verifyExpiration fails or token is not found.
state_output
intermediate
2:00remaining
What is the value of the new access token after refresh?
Given this snippet from a refresh token service, what will be the value of the new access token returned?
Spring Boot
public String generateTokenFromUsername(String username) {
    return Jwts.builder()
        .setSubject(username)
        .setIssuedAt(new Date())
        .setExpiration(new Date(System.currentTimeMillis() + 600000))
        .signWith(SignatureAlgorithm.HS512, jwtSecret)
        .compact();
}

// Assume username = "alice" and jwtSecret = "secretKey"
AA plain string 'alice' without any token structure
BA JWT token string with subject 'alice' and expiration 10 minutes from now
CAn empty string because jwtSecret is invalid
DA token string with subject 'secretKey' instead of 'alice'
Attempts:
2 left
💡 Hint
The method builds a JWT with the username as subject and signs it.
📝 Syntax
advanced
2:30remaining
Which option correctly defines a RefreshToken entity with expiration date?
Choose the correct Java entity class definition for a RefreshToken with fields: id (Long), token (String), expiryDate (Instant), and user (User).
A
public class RefreshToken {
  @Id
  private Long id;
  private String token;
  private Instant expiryDate;
  @OneToOne
  private User user;
}
B
public class RefreshToken {
  private Long id;
  private String token;
  private Date expiryDate;
  @OneToOne
  private User user;
}
C
public class RefreshToken {
  @Id
  private Long id;
  private String token;
  private Instant expiryDate;
  @ManyToOne
  private User user;
}
D
public class RefreshToken {
  @Id
  private Long id;
  private String token;
  private LocalDate expiryDate;
  @ManyToOne
  private User user;
}
Attempts:
2 left
💡 Hint
Check the correct annotation for user relationship and the type for expiryDate.
🔧 Debug
advanced
2:00remaining
Why does this refresh token validation code throw NullPointerException?
Examine this code snippet that validates a refresh token. Why does it throw NullPointerException sometimes?
Spring Boot
public RefreshToken verifyExpiration(RefreshToken token) {
    if (token.getExpiryDate().compareTo(Instant.now()) < 0) {
        refreshTokenRepository.delete(token);
        throw new TokenRefreshException(token.getToken(), "Refresh token expired");
    }
    return token;
}

// token can be null if not found in DB
ABecause token is null and token.getExpiryDate() causes NullPointerException
BBecause Instant.now() returns null causing NullPointerException
CBecause refreshTokenRepository.delete(token) is null causing NullPointerException
DBecause token.getExpiryDate() is null causing NullPointerException
Attempts:
2 left
💡 Hint
Consider what happens if the token argument is null.
🧠 Conceptual
expert
2:30remaining
What is the main security benefit of using a refresh token pattern in Spring Boot?
Why do applications use refresh tokens instead of just long-lived access tokens?
ARefresh tokens allow short-lived access tokens, reducing risk if access token is stolen
BRefresh tokens eliminate the need for user authentication entirely
CRefresh tokens store user passwords securely on the client side
DRefresh tokens allow unlimited access without expiration
Attempts:
2 left
💡 Hint
Think about what happens if an access token is stolen and how refresh tokens help.

Practice

(1/5)
1.

What is the main purpose of using a refresh token in a Spring Boot authentication system?

easy
A. To encrypt user data in the database
B. To store user passwords securely
C. To log out users automatically after a timeout
D. To allow users to get a new access token without logging in again

Solution

  1. Step 1: Understand the role of refresh tokens

    Refresh tokens are used to get new access tokens without asking the user to log in again.
  2. Step 2: Compare options with this purpose

    Only To allow users to get a new access token without logging in again describes this purpose correctly; others describe unrelated functions.
  3. Final Answer:

    To allow users to get a new access token without logging in again -> Option D
  4. Quick Check:

    Refresh token purpose = renew access token [OK]
Hint: Refresh tokens renew access tokens without re-login [OK]
Common Mistakes:
  • Confusing refresh token with password storage
  • Thinking refresh token logs out users
  • Assuming refresh token encrypts data
2.

Which of the following is the correct way to define a method in a Spring Boot controller to handle refresh token requests?

@PostMapping("/refresh")
public ResponseEntity<TokenResponse> refreshToken(@RequestBody RefreshRequest request) {
    // method body
}
easy
A. @GetMapping("/refresh") public TokenResponse refreshToken(@RequestBody RefreshRequest request)
B. @PostMapping("/refresh") public void refreshToken(String token)
C. @PostMapping("/refresh") public ResponseEntity<TokenResponse> refreshToken(@RequestBody RefreshRequest request)
D. @RequestMapping("/refresh") public String refreshToken()

Solution

  1. Step 1: Check HTTP method and parameters

    The refresh token request should be a POST with a JSON body containing the refresh token.
  2. Step 2: Match method signature

    @PostMapping("/refresh") public ResponseEntity<TokenResponse> refreshToken(@RequestBody RefreshRequest request) correctly uses @PostMapping, returns ResponseEntity<TokenResponse>, and accepts @RequestBody RefreshRequest.
  3. Final Answer:

    @PostMapping("/refresh") public ResponseEntity<TokenResponse> refreshToken(@RequestBody RefreshRequest request) -> Option C
  4. Quick Check:

    Correct POST method and request body = @PostMapping("/refresh") public ResponseEntity<TokenResponse> refreshToken(@RequestBody RefreshRequest request) [OK]
Hint: Refresh token requests use POST with @RequestBody [OK]
Common Mistakes:
  • Using GET instead of POST
  • Missing @RequestBody annotation
  • Wrong return type or parameters
3.

Given the following Spring Boot service method, what will be the output if the refresh token is invalid?

public TokenResponse refreshAccessToken(String refreshToken) {
    if (!tokenRepository.existsByToken(refreshToken)) {
        throw new RuntimeException("Invalid refresh token");
    }
    // generate new access token
    return new TokenResponse("newAccessToken");
}
medium
A. Throws RuntimeException with message "Invalid refresh token"
B. Returns a new TokenResponse with "newAccessToken"
C. Returns null
D. Returns the old refresh token

Solution

  1. Step 1: Analyze the token existence check

    The method checks if the refresh token exists in the repository; if not, it throws an exception.
  2. Step 2: Determine behavior on invalid token

    Since the token is invalid, the method throws RuntimeException with the message "Invalid refresh token".
  3. Final Answer:

    Throws RuntimeException with message "Invalid refresh token" -> Option A
  4. Quick Check:

    Invalid token triggers exception = Throws RuntimeException with message "Invalid refresh token" [OK]
Hint: Invalid refresh token causes exception throw [OK]
Common Mistakes:
  • Assuming method returns null on invalid token
  • Thinking it returns old token instead
  • Ignoring exception throwing
4.

Identify the error in this Spring Boot refresh token controller method:

@PostMapping("/refresh")
public ResponseEntity<TokenResponse> refreshToken(@RequestParam String refreshToken) {
    TokenResponse token = authService.refreshAccessToken(refreshToken);
    return ResponseEntity.ok(token);
}

What is the problem?

medium
A. Using @RequestParam instead of @RequestBody for refresh token
B. Missing @PostMapping annotation
C. Returning ResponseEntity instead of TokenResponse
D. Calling wrong service method

Solution

  1. Step 1: Check parameter annotation

    The refresh token is usually sent in the request body as JSON, not as a query parameter.
  2. Step 2: Identify correct annotation

    The method should use @RequestBody instead of @RequestParam to receive the refresh token properly.
  3. Final Answer:

    Using @RequestParam instead of @RequestBody for refresh token -> Option A
  4. Quick Check:

    Refresh token needs @RequestBody, not @RequestParam [OK]
Hint: Refresh token comes in body, use @RequestBody [OK]
Common Mistakes:
  • Using query parameters for refresh token
  • Confusing ResponseEntity with return type
  • Missing or wrong annotations
5.

You want to implement a refresh token mechanism in Spring Boot that invalidates the old refresh token after use and issues a new one along with the access token. Which approach below correctly achieves this?

hard
A. Check refresh token validity, generate new access token, keep old refresh token unchanged
B. Generate new access token and new refresh token, save new refresh token, delete old refresh token
C. Generate new access token only, do not check refresh token validity
D. Delete refresh token without issuing new tokens

Solution

  1. Step 1: Understand token rotation

    To improve security, the old refresh token should be invalidated and replaced with a new one after use.
  2. Step 2: Identify correct token handling

    Generate new access token and new refresh token, save new refresh token, delete old refresh token correctly generates new access and refresh tokens, saves the new refresh token, and deletes the old one.
  3. Final Answer:

    Generate new access token and new refresh token, save new refresh token, delete old refresh token -> Option B
  4. Quick Check:

    Refresh token rotation = Generate new access token and new refresh token, save new refresh token, delete old refresh token [OK]
Hint: Rotate refresh tokens: new token saved, old token deleted [OK]
Common Mistakes:
  • Not invalidating old refresh token
  • Skipping refresh token validity check
  • Deleting tokens without issuing new ones