版本
spring-security:6.2.1
方案
添加过滤器检查会话认证信息,如果包含非匿名用户的认证信息则调用认证成功处理器
final static String URL_LOGIN = "/login";
final AuthenticationSuccessHandler authenticationSuccessHandler = new SavedRequestAwareAuthenticationSuccessHandler();
@Bean
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http
) {// 表单登录http.formLogin(formLogin -> {formLogin.loginPage(URL_LOGIN);formLogin.permitAll();formLogin.successHandler(authenticationSuccessHandler);});...
}
// 登录页过滤器
@Bean
Filter loginPageFilter() {return new OncePerRequestFilter() {@Overrideprotected void doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {Authentication authorization = SecurityContextHolder.getContext().getAuthentication();if (authorization != null&& authorization.isAuthenticated()&& !(authorization instanceof AnonymousAuthenticationToken)&& request.getRequestURI().equals(URL_LOGIN)) {log.debug("user is authenticated but trying to access login page, redirecting to cached request");authenticationSuccessHandler.onAuthenticationSuccess(request, response, authorization);}filterChain.doFilter(request, response);}};
}