Refresh token pattern in Spring Boot - Mini Project: Build & Apply
Start learning this pattern below
Jump into concepts and practice - no test required
RefreshToken with two fields: String token and Instant expiryDate.Use a Java record to hold the token string and its expiry date.
long variables called accessTokenExpirationMs and refreshTokenExpirationMs with values 900000 and 604800000 respectively to represent expiration times in milliseconds.Set access token expiration to 15 minutes (900000 ms) and refresh token expiration to 7 days (604800000 ms).
generateRefreshToken that returns a RefreshToken. It should create a random UUID string for the token and set the expiry date to the current time plus refreshTokenExpirationMs milliseconds.Use UUID.randomUUID().toString() for token and Instant.now().plusMillis() for expiry.
refreshAccessToken that accepts a String refreshToken parameter. It should validate the token expiry by comparing with Instant.now() and return a new access token string if valid. Use accessTokenExpirationMs to set the new token expiry time.Check if the refresh token expiry is before now to reject expired tokens. Return a new UUID string as the access token.
Practice
What is the main purpose of using a refresh token in a Spring Boot authentication system?
Solution
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.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.Final Answer:
To allow users to get a new access token without logging in again -> Option DQuick Check:
Refresh token purpose = renew access token [OK]
- Confusing refresh token with password storage
- Thinking refresh token logs out users
- Assuming refresh token encrypts data
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
}Solution
Step 1: Check HTTP method and parameters
The refresh token request should be a POST with a JSON body containing the refresh token.Step 2: Match method signature
@PostMapping("/refresh") public ResponseEntity<TokenResponse> refreshToken(@RequestBody RefreshRequest request) correctly uses @PostMapping, returns ResponseEntity<TokenResponse>, and accepts @RequestBody RefreshRequest.Final Answer:
@PostMapping("/refresh") public ResponseEntity<TokenResponse> refreshToken(@RequestBody RefreshRequest request) -> Option CQuick Check:
Correct POST method and request body = @PostMapping("/refresh") public ResponseEntity<TokenResponse> refreshToken(@RequestBody RefreshRequest request) [OK]
- Using GET instead of POST
- Missing @RequestBody annotation
- Wrong return type or parameters
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");
}Solution
Step 1: Analyze the token existence check
The method checks if the refresh token exists in the repository; if not, it throws an exception.Step 2: Determine behavior on invalid token
Since the token is invalid, the method throws RuntimeException with the message "Invalid refresh token".Final Answer:
Throws RuntimeException with message "Invalid refresh token" -> Option AQuick Check:
Invalid token triggers exception = Throws RuntimeException with message "Invalid refresh token" [OK]
- Assuming method returns null on invalid token
- Thinking it returns old token instead
- Ignoring exception throwing
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?
Solution
Step 1: Check parameter annotation
The refresh token is usually sent in the request body as JSON, not as a query parameter.Step 2: Identify correct annotation
The method should use @RequestBody instead of @RequestParam to receive the refresh token properly.Final Answer:
Using @RequestParam instead of @RequestBody for refresh token -> Option AQuick Check:
Refresh token needs @RequestBody, not @RequestParam [OK]
- Using query parameters for refresh token
- Confusing ResponseEntity with return type
- Missing or wrong annotations
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?
Solution
Step 1: Understand token rotation
To improve security, the old refresh token should be invalidated and replaced with a new one after use.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.Final Answer:
Generate new access token and new refresh token, save new refresh token, delete old refresh token -> Option BQuick Check:
Refresh token rotation = Generate new access token and new refresh token, save new refresh token, delete old refresh token [OK]
- Not invalidating old refresh token
- Skipping refresh token validity check
- Deleting tokens without issuing new ones
