SpringBoot3中UsernamePasswordAuthenticationFilter与SimpleUrlLogoutSuccessHandler失效
SpringBoot3迁移后自定义登录过滤器失效的解决方案
问题根源
SpringBoot3配套的Spring Security 6重构了认证流程的配置机制,原SpringBoot2中直接注册UsernamePasswordAuthenticationFilter的方式不再适配,导致自定义过滤器无法参与认证流程,最终登录功能失效。
修复方案
1. 重构SecurityFilterChain配置
废弃原WebSecurityConfigurerAdapter的继承方式,改用组件式SecurityFilterChain配置,正确注入自定义过滤器:
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers("/login", "/logout").permitAll() .anyRequest().authenticated() ) .addFilterBefore(customAuthFilter(), UsernamePasswordAuthenticationFilter.class) .logout(logout -> logout .logoutSuccessHandler(customLogoutHandler()) .permitAll() ); return http.build(); }
2. 正确配置自定义认证过滤器
为自定义过滤器绑定AuthenticationManager,确保认证逻辑能被触发:
@Bean public CustomAuthenticationFilter customAuthFilter() throws Exception { CustomAuthenticationFilter filter = new CustomAuthenticationFilter(); AuthenticationManager authManager = authenticationManager(http.getSharedObject(AuthenticationConfiguration.class)); filter.setAuthenticationManager(authManager); // 配置成功/失败处理器 filter.setAuthenticationSuccessHandler((req, res, auth) -> res.setStatus(HttpServletResponse.SC_OK)); filter.setAuthenticationFailureHandler((req, res, ex) -> res.setStatus(HttpServletResponse.SC_UNAUTHORIZED)); return filter; } @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception { return config.getAuthenticationManager(); }
3. 适配自定义认证Token的Provider
确保AuthenticationProvider明确支持自定义Token类型,避免认证流程跳过自定义逻辑:
@Bean public AuthenticationProvider customAuthProvider() { return new AuthenticationProvider() { @Override public Authentication authenticate(Authentication auth) throws AuthenticationException { CustomAuthenticationToken token = (CustomAuthenticationToken) auth; // 实现tenant+用户名+密码的校验逻辑 if (isValid(token.getTenant(), token.getName(), token.getCredentials().toString())) { return new UsernamePasswordAuthenticationToken(token.getName(), null, Collections.emptyList()); } throw new BadCredentialsException("无效凭证"); } @Override public boolean supports(Class<?> authClass) { return CustomAuthenticationToken.class.isAssignableFrom(authClass); } }; }
4. 登出处理器的兼容配置
保持SimpleUrlLogoutSuccessHandler的配置,通过logoutSuccessHandler注入即可:
@Bean public SimpleUrlLogoutSuccessHandler customLogoutHandler() { SimpleUrlLogoutSuccessHandler handler = new SimpleUrlLogoutSuccessHandler(); handler.setDefaultTargetUrl("/logout-success"); return handler; }
核心注意事项
- Spring Security 6彻底移除了
WebSecurityConfigurerAdapter,必须使用SecurityFilterChain进行配置。 - 自定义过滤器必须绑定
AuthenticationManager,否则无法触发认证流程。 AuthenticationProvider的supports方法必须准确匹配自定义Token类型,否则自定义认证逻辑会被忽略。
内容的提问来源于stack exchange,提问作者P. Ottlinger
相关产品推荐
相关产品推荐

