Hello! Let's continue strengthening our application's security.
In our last lesson, we took a major step forward by moving our access token into a secure, HttpOnly cookie to protect against XSS attacks. While secure, this setup has a critical limitation: once the access token expires, the user is effectively logged out and must re-authenticate. This creates a poor user experience.
Today, we'll implement the industry-standard solution to this problem. Our lesson is built around the learning outcome: Implement a token refresh endpoint that validates a refresh token and issues a new access token. We will introduce a second, long-lived refresh token to allow our application to seamlessly renew sessions without requiring the user to constantly log in.
The Access & Refresh Token Architecture
The core idea is to use two separate tokens:
- Access Token: Short-lived (e.g., 15-60 minutes). Used to access protected resources. If stolen, its value is limited by its short lifespan.
- Refresh Token: Long-lived (e.g., 7-30 days). Its only purpose is to obtain a new access token. It is stored securely and used infrequently.
The flow looks like this:

MERN-to-Spring Mapping: The Refresh Route
In a MERN stack, you'd create a new route, say /api/auth/refresh, in an Express router. That route handler would receive the refresh token (likely from a cookie), validate it against a database (perhaps Redis or MongoDB), and if valid, sign a new access token using jsonwebtoken. The concept we're implementing today is identical; we're just using Spring's components—Controllers, Services, and JPA Repositories—to build it.
1. Refactoring for a Two-Token System
To implement this pattern, we'll refactor our previous work. Our goal is to store the long-lived refresh token in the HttpOnly cookie, while the short-lived access token will be returned in the response body to be held in memory by the client.
Step 1: Update Application Properties
Let's define separate expiration times for our tokens. Open src/main/resources/application.properties and add a new property for the refresh token's expiration.
# src/main/resources/application.properties
# ... other properties
# JWT Properties
# Access token validity: 1 hour (3600000 ms)
app.jwt.access-token-expiration-ms=3600000
# Refresh token validity: 7 days (604800000 ms)
app.jwt.refresh-token-expiration-ms=604800000
app.jwt.secret=your-super-strong-and-long-secret-key-that-is-at-least-256-bits
Note: I've namespaced the properties under app.jwt.* for better organization.
Step 2: Update JwtService
Now, let's update JwtService to read these new properties and generate both types of tokens.
// src/main/java/com/example/blogplatform/service/JwtService.java
package com.example.blogplatform.service;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
@Service
public class JwtService {
@Value("${app.jwt.secret}")
private String secretKey;
@Value("${app.jwt.access-token-expiration-ms}")
private long accessTokenExpiration;
@Value("${app.jwt.refresh-token-expiration-ms}")
private long refreshTokenExpiration;
// ... existing methods: extractUsername, isTokenValid etc.
public String generateToken(UserDetails userDetails) {
return buildToken(new HashMap<>(), userDetails, accessTokenExpiration);
}
public String generateRefreshToken(UserDetails userDetails) {
return buildToken(new HashMap<>(), userDetails, refreshTokenExpiration);
}
private String buildToken(
Map<String, Object> extraClaims,
UserDetails userDetails,
long expiration
) {
return Jwts
.builder()
.setClaims(extraClaims)
.setSubject(userDetails.getUsername())
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + expiration))
.signWith(getSignInKey(), SignatureAlgorithm.HS256)
.compact();
}
// ... rest of the class
}
We've added generateRefreshToken and a private buildToken helper to avoid code duplication.
Step 3: Refactor the JwtAuthenticationFilter
Since the access token will now be sent in the Authorization: Bearer <token> header by the client, we must revert our filter to look there primarily. The cookie is now reserved for the refresh flow.
// src/main/java/com/example/blogplatform/config/JwtAuthenticationFilter.java
// ... imports
@Override
protected void doFilterInternal(
@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response,
@NonNull FilterChain filterChain
) throws ServletException, IOException {
final String authHeader = request.getHeader("Authorization");
final String jwt;
final String userEmail;
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
filterChain.doFilter(request, response);
return;
}
jwt = authHeader.substring(7);
userEmail = jwtService.extractUsername(jwt);
if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail);
if (jwtService.isTokenValid(jwt, userDetails)) {
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
userDetails,
null,
userDetails.getAuthorities()
);
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}
filterChain.doFilter(request, response);
}
This simplifies the filter back to its conventional form, which is what we need for this new architecture.
2. Persisting Refresh Tokens for Invalidation
A crucial aspect of a production-grade system is the ability to invalidate tokens. What if a user's refresh token is stolen? We need a way to revoke it. The only reliable way to do this is to store a reference to it on the server side.
Let's create a RefreshToken entity, repository, and service to manage this.
Spring Boot Refresh Token with JWT example - BezKoder
The article 'Spring Boot Refresh Token with JWT example' from BezKoder provides a clear and structured guide on how to create the necessary components for managing refresh tokens in a database. We'll follow its lead.
Please read the section 'Create Refresh Token Service', including its subsections 'Refresh Token class', 'Refresh Token Repository', and 'Refresh Token Service'. This covers the exact three components we are about to build: the entity model, the JPA repository, and the service class that orchestrates the logic.
Step 1: RefreshToken Entity
Create a new file for our entity.
// src/main/java/com/example/blogplatform/model/RefreshToken.java
package com.example.blogplatform.model;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.Instant;
@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class RefreshToken {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String token;
@Column(nullable = false)
private Instant expiryDate;
@OneToOne
@JoinColumn(name = "user_id", referencedColumnName = "id")
private User user;
}
Step 2: RefreshTokenRepository
Create the corresponding JPA repository.
// src/main/java/com/example/blogplatform/repository/RefreshTokenRepository.java
package com.example.blogplatform.repository;
import com.example.blogplatform.model.RefreshToken;
import com.example.blogplatform.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface RefreshTokenRepository extends JpaRepository<RefreshToken, Long> {
Optional<RefreshToken> findByToken(String token);
int deleteByUser(User user); // We'll use this for logout later
}
Step 3: RefreshTokenService
This service will encapsulate the logic for creating, finding, and verifying our database-stored tokens.
// src/main/java/com/example/blogplatform/service/RefreshTokenService.java
package com.example.blogplatform.service;
import com.example.blogplatform.model.RefreshToken;
import com.example.blogplatform.repository.RefreshTokenRepository;
import com.example.blogplatform.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;
@Service
@RequiredArgsConstructor
public class RefreshTokenService {
private final RefreshTokenRepository refreshTokenRepository;
private final UserRepository userRepository;
@Value("${app.jwt.refresh-token-expiration-ms}")
private Long refreshTokenDurationMs;
public Optional<RefreshToken> findByToken(String token) {
return refreshTokenRepository.findByToken(token);
}
public RefreshToken createRefreshToken(String username) {
User user = userRepository.findByEmail(username)
.orElseThrow(() -> new RuntimeException("User not found"));
// Let's delete any existing refresh token for the user
refreshTokenRepository.deleteByUser(user);
RefreshToken refreshToken = RefreshToken.builder()
.user(user)
.token(UUID.randomUUID().toString())
.expiryDate(Instant.now().plusMillis(refreshTokenDurationMs))
.build();
return refreshTokenRepository.save(refreshToken);
}
public RefreshToken verifyExpiration(RefreshToken token) {
if (token.getExpiryDate().compareTo(Instant.now()) < 0) {
refreshTokenRepository.delete(token);
throw new RuntimeException(token.getToken() + " Refresh token was expired. Please make a new signin request");
}
return token;
}
}
Architectural Note: In createRefreshToken, we delete any old refresh tokens for that user. This is a security measure to ensure only one active refresh token exists per user session, preventing old, potentially compromised tokens from being used.
3. Building the Refresh Token Endpoint
Now we have all the pieces to build the endpoint itself.
Implementing Secure Refresh Tokens in Spring Boot | #2 | Spring Boot JWT
The video 'Implementing Secure Refresh Tokens in Spring Boot' by Learn With Ifte provides a concise walkthrough of creating the controller endpoint and whitelisting it in the security configuration.
Please watch from 00:00 to 01:17 to see how the /refresh_token endpoint is defined in the controller. Then, watch from 07:44 to 08:06 to see how this new endpoint is added to the security configuration to allow public access.
Step 1: Update the login Endpoint
Let's modify the login method in AuthController to return the access token in the body and set the refresh token in an HttpOnly cookie.
First, we need a response DTO.
// src/main/java/com/example/blogplatform/payload/response/JwtResponse.java
package com.example.blogplatform.payload.response;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class JwtResponse {
private String accessToken;
}
Now, update AuthController.
// src/main/java/com/example/blogplatform/controller/AuthController.java
// ... other imports
import com.example.blogplatform.payload.response.JwtResponse;
import com.example.blogplatform.service.RefreshTokenService;
import jakarta.servlet.http.HttpServletResponse;
// ...
@RestController
@RequestMapping("/api/v1/auth")
@RequiredArgsConstructor
public class AuthController {
private final AuthenticationService authenticationService;
private final RefreshTokenService refreshTokenService;
private final JwtService jwtService;
// ...
@PostMapping("/login")
public ResponseEntity<JwtResponse> login(@RequestBody LoginRequest request, HttpServletResponse response) {
// Authenticate user and get UserDetails
UserDetails userDetails = authenticationService.authenticateAndGetUser(request);
// Generate tokens
String accessToken = jwtService.generateToken(userDetails);
RefreshToken refreshToken = refreshTokenService.createRefreshToken(userDetails.getUsername());
// Set refresh token in HttpOnly cookie
final String refreshTokenCookieName = "refreshToken";
String cookieHeader = String.format(
"%s=%s; Max-Age=%d; Path=/; HttpOnly; Secure; SameSite=Strict",
refreshTokenCookieName, refreshToken.getToken(), 604800 // 7 days in seconds
);
response.addHeader("Set-Cookie", cookieHeader);
// Return access token in response body
return ResponseEntity.ok(new JwtResponse(accessToken));
}
}
Note: We also need to slightly refactor AuthenticationService to return UserDetails upon successful authentication.
Step 2: Create the /refresh Endpoint
Now for the main event. Add the new endpoint to AuthController.
// In AuthController.java
// ...
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Optional;
// ...
@PostMapping("/refresh")
public ResponseEntity<JwtResponse> refreshToken(HttpServletRequest request) {
// 1. Extract refresh token from cookie
String refreshTokenString = Arrays.stream(request.getCookies())
.filter(cookie -> "refreshToken".equals(cookie.getName()))
.map(Cookie::getValue)
.findFirst()
.orElseThrow(() -> new RuntimeException("Refresh token not found in cookie"));
// 2. Find and verify token in DB
return refreshTokenService.findByToken(refreshTokenString)
.map(refreshTokenService::verifyExpiration)
.map(RefreshToken::getUser)
.map(user -> {
// 3. Generate new access token
String newAccessToken = jwtService.generateToken(user);
return ResponseEntity.ok(new JwtResponse(newAccessToken));
})
.orElseThrow(() -> new RuntimeException("Refresh token is not in database!"));
}
This elegant chain of .map() calls on the Optional returned from the database is a common and clean pattern in modern Java.
Step 3: Whitelist the Endpoint
Finally, we must allow unauthenticated access to our new /refresh endpoint in SecurityConfig.
// src/main/java/com/example/blogplatform/config/SecurityConfig.java
// ...
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(req -> req
.requestMatchers("/api/v1/auth/**") // Whitelists /login, /register, AND /refresh
.permitAll()
.requestMatchers("/api/v1/admin/**").hasRole("ADMIN")
.anyRequest()
.authenticated()
)
// ... rest of the config
return http.build();
}
Since our endpoint is at /api/v1/auth/refresh, the existing "/api/v1/auth/**" rule already covers it. No changes needed if you have this pattern!
4. Runtime Observation & Debugging Task
Let's test the entire flow.
- Restart your application.
- Using Postman, send a
POSTrequest to/api/v1/auth/login.- Observe: The response body contains the
accessToken. TheHeaderstab of the response shows aSet-Cookieheader for therefreshToken.
- Observe: The response body contains the
- Copy the
accessTokenfrom the response body. - Send a
GETrequest to a protected endpoint (e.g.,/api/v1/test/userif you have one), adding anAuthorizationheader with the valueBearer <your_access_token>. It should succeed. - Now, to simulate expiration, either wait for the token to expire or, for faster testing, restart the app with a very short
app.jwt.access-token-expiration-ms(e.g.,10000for 10 seconds). - After the access token expires, repeat step 4.
- Observe: You should now get a
403 Forbiddenor401 Unauthorizederror.
- Observe: You should now get a
- Your Debugging Task:
- Set a breakpoint inside the
refreshTokenmethod in yourAuthController. - Now, send a
POSTrequest to/api/v1/auth/refresh. Postman will automatically send therefreshTokencookie it received during login. - Observe: Your breakpoint should hit. Inspect the
request.getCookies()array. You should see therefreshTokencookie. Step through the logic: see the token being extracted, validated against the database, and finally, a new access token being generated and returned in theJwtResponse.
- Set a breakpoint inside the
- Take the
newAccessTokenfrom the response of the/refreshcall and use it in theAuthorizationheader for your protected endpoint. It should now succeed again.
You have successfully implemented a seamless and secure session refresh mechanism!
Conclusion
In this lesson, we've implemented one of the most critical features of a modern authentication system. We've moved from a single, insecure token model to a robust, production-grade access and refresh token architecture.
Key Takeaways:
- Two-Token Strategy: Short-lived access tokens for security, long-lived refresh tokens for user experience.
- Secure Storage: The refresh token is stored in a secure,
HttpOnlycookie, while the access token is returned to the client to be held in memory. - Server-Side Invalidation: Persisting refresh tokens in a database is essential for enabling server-side revocation (e.g., on logout).
- The Refresh Flow: An unauthenticated
/refreshendpoint validates the refresh token from a cookie and issues a new access token.
Preview of the Next Lesson:
We've built the infrastructure to store refresh tokens. What's the immediate benefit? We can now build a proper logout feature. In the next lesson, we will build a logout mechanism that invalidates the refresh token on the server-side, ensuring that once a user logs out, their session is truly terminated.