How to Return JWT Tokens Directly After Spring Security Login
This tutorial explains how to integrate JWT with Spring Security so that a successful login returns a JWT token instead of a page redirect, covering the authentication flow, custom success and failure handlers, configuration steps, and verification of the returned JSON responses.
1. Introduction
Welcome to the Spring Security practical series. After implementing a JWT utility in the previous article, we now explore how to combine JWT with Spring Security so that a successful authentication returns a JWT token directly.
2. Flow
JWT is suitable for front‑back separation. After a successful login the system returns a JwtTokenPair containing an access token and a refresh token; on failure it returns authentication‑failure information.
3.1 AuthenticationSuccessHandler returns JWT Token
The AuthenticationSuccessHandler processes successful logins. It is defined as a Spring bean, builds a response map with time, flag, username, roles, and the generated JWT tokens, and writes the JSON back to the client.
/**
* 处理登录成功后返回 JWT Token 对.
*
* @param jwtTokenGenerator the jwt token generator
* @return the authentication success handler
*/
@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler(JwtTokenGenerator jwtTokenGenerator) {
return (request, response, authentication) -> {
if (response.isCommitted()) {
log.debug("Response has already been committed");
return;
}
Map<String, Object> map = new HashMap<>(5);
map.put("time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
map.put("flag", "success_login");
User principal = (User) authentication.getPrincipal();
String username = principal.getUsername();
Collection<GrantedAuthority> authorities = principal.getAuthorities();
Set<String> roles = new HashSet<>();
if (CollectionUtil.isNotEmpty(authorities)) {
for (GrantedAuthority authority : authorities) {
String roleName = authority.getAuthority();
roles.add(roleName);
}
}
JwtTokenPair jwtTokenPair = jwtTokenGenerator.jwtTokenPair(username, roles, null);
map.put("access_token", jwtTokenPair.getAccessToken());
map.put("refresh_token", jwtTokenPair.getRefreshToken());
ResponseUtil.responseJsonWriter(response, RestBody.okData(map, "登录成功"));
};
}3.2 AuthenticationFailureHandler returns failure info
The AuthenticationFailureHandler handles login failures. It also registers as a Spring bean, builds a response map with time and a failure flag, and returns a 401 JSON payload.
/**
* 失败登录处理器 处理登录失败后的逻辑 登录失败返回信息 以此为依据跳转
*
* @return the authentication failure handler
*/
@Bean
public AuthenticationFailureHandler authenticationFailureHandler() {
return (request, response, exception) -> {
if (response.isCommitted()) {
log.debug("Response has already been committed");
return;
}
Map<String, Object> map = new HashMap<>(2);
map.put("time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
map.put("flag", "failure_login");
ResponseUtil.responseJsonWriter(response, RestBody.build(HttpStatus.UNAUTHORIZED.value(), map, "认证失败", "-9999"));
};
}4. Configuration
Register the two handler beans in the login configuration:
httpSecurity.formLogin()
.loginProcessingUrl(LOGIN_PROCESSING_URL)
.successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler);5. Verification
Run the test cases from the previous article. A successful login returns JSON containing access_token, refresh_token, time and a success_login flag. The token can be decoded with jwt.io . A failed login returns a 401 JSON with a failure_login flag.
{
"httpStatus": 200,
"data": {
"access_token": "eyJhbGciOi...",
"refresh_token": "eyJhbGciOi...",
"time": "2019-10-28 11:32:11",
"flag": "success_login"
},
"msg": "登录成功",
"identifier": ""
} {
"httpStatus": 401,
"data": {
"time": "2019-10-28 12:54:10",
"flag": "failure_login"
},
"msg": "认证失败",
"identifier": "-9999"
}Decoding the access_token with jwt.io yields the token payload shown below:
6. Summary
We have linked JWT with Spring Security, enabling a login to return a JWT token directly. This is only the beginning; the next article will cover how the client uses the token and how the server validates it.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
