The refresh token pattern helps keep users logged in safely without asking for their password again and again.
Refresh token pattern in Spring Boot
POST /auth/refresh
Headers:
Authorization: Bearer <refresh_token>
Response:
{
"accessToken": "newAccessToken",
"refreshToken": "newRefreshToken"
}The client sends the refresh token to get a new access token.
The server verifies the refresh token and returns new tokens if valid.
POST /auth/refresh Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
{
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "dGhpc2lzYXJlZnJlc2h0b2tlbg=="
}This Spring Boot controller has a POST endpoint at /auth/refresh.
It reads the refresh token from the Authorization header.
If the token is valid, it returns new access and refresh tokens as JSON.
If invalid, it returns 401 Unauthorized.
package com.example.demo.security; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController public class AuthController { @PostMapping("/auth/refresh") public ResponseEntity<Map<String, String>> refreshToken(@RequestHeader("Authorization") String authorizationHeader) { // Extract token from header String refreshToken = authorizationHeader.replace("Bearer ", ""); // Here, normally verify the refresh token validity if (!isValidRefreshToken(refreshToken)) { return ResponseEntity.status(401).build(); } // Generate new tokens (dummy tokens for example) String newAccessToken = "newAccessToken123"; String newRefreshToken = "newRefreshToken456"; Map<String, String> tokens = new HashMap<>(); tokens.put("accessToken", newAccessToken); tokens.put("refreshToken", newRefreshToken); return ResponseEntity.ok(tokens); } private boolean isValidRefreshToken(String token) { // Dummy check: accept only "validRefreshToken" return "validRefreshToken".equals(token); } }
Always keep refresh tokens secure and store them safely on the client side.
Refresh tokens usually have longer expiry than access tokens.
Revoke refresh tokens if suspicious activity is detected.
The refresh token pattern helps keep users logged in securely without asking for passwords repeatedly.
Clients send refresh tokens to get new access tokens when old ones expire.
Servers verify refresh tokens and issue new tokens if valid.