处理认证成功后的逻辑AuthenticationSuccessHandler
大约 1 分钟
AuthenticationSuccessHandler
处理认证成功后的逻辑1、简介
AuthenticationSuccessHandler
是一个接口,定义了当用户成功登录后需要执行的操作。常见的实现方式是重定向到一个特定的页面,或者执行一些后处理逻辑。
处理场景如下:
- 登录成功后的页面跳转
- 登录成功后执行一些业务逻辑(例如记录日志、触发事件等)
2、源码
public interface AuthenticationSuccessHandler {
default void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {
this.onAuthenticationSuccess(request, response, authentication);
chain.doFilter(request, response);
}
void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException;
}
参数说明:
HttpServletRequest request
:当前的请求对象。HttpServletResponse response
:当前的响应对象。Authentication authentication
:认证成功后,包含用户信息的Authentication
对象,通常是一个UsernamePasswordAuthenticationToken
实例。
3、实现案例
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain,
Authentication authentication) throws IOException, ServletException {
AuthenticationSuccessHandler.super.onAuthenticationSuccess(request, response, chain, authentication);
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
//获取用户身份信息
Object principal = authentication.getPrincipal();
//创建结果对象
Map<String, Object> result = new HashMap<>();
result.put("code", 0);
result.put("message", "登录成功");
result.put("data", principal);
//转换成json字符串
String json = JSON.toJSONString(result);
//返回响应
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(json);
}
}
配置
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// 开启授权保护
.authorizeHttpRequests(authorize -> authorize
.anyRequest()//对所有请求开启授权保护
.authenticated()//已认证的请求会被自动授权
)
//自定义登录页面
.formLogin(form -> form.loginPage("/login").permitAll()
.successHandler(new MyAuthenticationSuccessHandler()) //认证成功时的处理
.failureHandler(new MyAuthenticationFailureHandler()) //认证失败时的处理
)//.permitAll() 解决localhost 将您重定向的次数过多
.httpBasic(withDefaults())//使用基本授权方式
.csrf(AbstractHttpConfigurer::disable)//关闭 csrf 攻击防御
;
return http.build();
}