java
42 lines · 7 steps
Issuing JWT and refresh tokens on login in Spring
A Spring Security success handler that mints an access token in the body and a hardened refresh-token cookie after login.
Explained by
highlit
1@Component
2public class RefreshTokenSuccessHandler implements AuthenticationSuccessHandler {
3
4 private final RefreshTokenService refreshTokenService;
5 private final JwtService jwtService;
6 private final ObjectMapper objectMapper;
7
8 @Value("${security.jwt.refresh-token-ttl:604800}")
9 private long refreshTokenTtlSeconds;
10
11 public RefreshTokenSuccessHandler(RefreshTokenService refreshTokenService,
12 JwtService jwtService,
13 ObjectMapper objectMapper) {
14 this.refreshTokenService = refreshTokenService;
15 this.jwtService = jwtService;
16 this.objectMapper = objectMapper;
17 }
18
19 @Override
20 public void onAuthenticationSuccess(HttpServletRequest request,
21 HttpServletResponse response,
22 Authentication authentication) throws IOException {
23 UserDetails user = (UserDetails) authentication.getPrincipal();
24
25 String accessToken = jwtService.issueAccessToken(user);
26 RefreshToken refreshToken = refreshTokenService.createFor(user.getUsername());
27
28 ResponseCookie cookie = ResponseCookie.from("refresh_token", refreshToken.getValue())
29 .httpOnly(true)
30 .secure(true)
31 .sameSite("Strict")
32 .path("/api/auth/refresh")
33 .maxAge(Duration.ofSeconds(refreshTokenTtlSeconds))
34 .build();
35 response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());
36
37 response.setStatus(HttpStatus.OK.value());
38 response.setContentType(MediaType.APPLICATION_JSON_VALUE);
39 objectMapper.writeValue(response.getWriter(),
40 Map.of("accessToken", accessToken, "tokenType", "Bearer"));
41 }
42}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Splitting tokens — short-lived access token in the body, long-lived refresh token in an HttpOnly cookie — limits the blast radius if either leaks.
- 2Scoping a cookie with HttpOnly, Secure, SameSite, and a narrow path hardens it against XSS and CSRF theft.
- 3Spring Security's AuthenticationSuccessHandler is the seam for customizing exactly what a successful login returns to the client.
Related explainers
java
public class TimedFetchService { private final ExecutorService executor = Executors.newFixedThreadPool(8); private final HttpClient httpClient = HttpClient.newHttpClient();
Enforcing HTTP timeouts with a Future
concurrency
timeouts
thread-pool
Intermediate
8 steps
python
from datetime import timedelta from flask import Blueprint, current_app, make_response, redirect, request, url_for from itsdangerous import URLSafeTimedSerializer, BadSignature, SignatureExpired
How signed remember-me cookies work in Flask
authentication
signed-cookies
session-management
Intermediate
8 steps
java
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.module.SimpleModule;
Serializing Money to JSON in Spring
serialization
jackson
money
Intermediate
8 steps
ruby
class ApplicationController < ActionController::Base ALLOWED_REDIRECT_HOSTS = [nil, ENV.fetch("APP_HOST", "app.example.com")].freeze def store_return_to(location = request.fullpath)
Safe post-login redirects in Rails
open-redirect
session
authentication
Intermediate
9 steps
java
@Component @Order(Ordered.HIGHEST_PRECEDENCE) public class TenantResolutionFilter extends OncePerRequestFilter {
How a tenant-resolution filter works in Spring
multi-tenancy
servlet-filter
thread-local
Intermediate
8 steps
java
@Repository public interface SubscriptionRepository extends JpaRepository<Subscription, Long> { @Modifying(clearAutomatically = true, flushAutomatically = true)
Bulk JPQL updates in a Spring Data repository
jpql
bulk-update
modifying-query
Intermediate
5 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/issuing-jwt-and-refresh-tokens-on-login-in-spring-explained-java-d757/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.