Spring Boot与Spring Security升级后自定义AuthenticationProvider未调用问题
Spring Boot 3.0.5 + Spring Security 6.0.2 自定义AuthenticationProvider未被调用的解决方案
核心问题分析
Spring Security 6.x对认证流程的配置逻辑做了调整,5.x的部分配置方式不再生效。你的自定义Provider未被调用,大概率是AuthenticationManager注册方式错误,或者请求未触发对应认证过滤器,也可能是自定义Provider的supports(Class<?>)方法未适配新的Authentication类型。
正确配置方式
方式1:通过AuthenticationManagerBuilder构建并注册到SecurityFilterChain
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // 构建包含自定义Provider的AuthenticationManager AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManagerBuilder.class) .authenticationProvider(customAuthenticationProvider()) .build(); http.csrf(csrf -> csrf.disable()) .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) .authenticationManager(authenticationManager) .formLogin(form -> form.permitAll()) .logout(logout -> logout.permitAll()); return http.build(); } @Bean public CustomAuthenticationProvider customAuthenticationProvider() { return new CustomAuthenticationProvider(); }
方式2:直接在HttpSecurity中添加AuthenticationProvider
Spring Security会自动将添加的Provider纳入全局AuthenticationManager,无需手动构建:
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf(csrf -> csrf.disable()) .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) .authenticationProvider(customAuthenticationProvider()) .formLogin(form -> form.permitAll()) .logout(logout -> logout.permitAll()); return http.build(); } @Bean public CustomAuthenticationProvider customAuthenticationProvider() { return new CustomAuthenticationProvider(); }
关键检查点
- 验证supports方法:确保自定义Provider的
supports方法返回true,匹配你使用的Authentication类型(比如UsernamePasswordAuthenticationToken):@Override public boolean supports(Class<?> authentication) { return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication); } - 确认请求触发认证:确保请求携带了对应认证凭证(如用户名密码、token),且对应的认证过滤器(如
UsernamePasswordAuthenticationFilter)已启用。 - 移除冗余配置:不要同时手动构建AuthenticationManager又调用
authenticationProvider(),避免配置冲突。
OAuth2资源服务器场景适配
如果是OAuth2资源服务器场景,需适配对应Authentication类型,同时确保authenticationManagerResolver配置正确:
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf(csrf -> csrf.disable()) .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) .oauth2ResourceServer(oauth2 -> oauth2 .authenticationManagerResolver(request -> { return http.getSharedObject(AuthenticationManagerBuilder.class) .authenticationProvider(customAuthenticationProvider()) .build(); }) ); return http.build(); }
内容的提问来源于stack exchange,提问作者RagaSGNur
相关产品推荐
相关产品推荐

