Spring Security报No AuthenticationProvider found认证错误问题问询
问题根因
你出现这个报错有两个核心问题:
- 你在
AppSecureConfig中定义的configure(AuthenticationManagerBuilder auth)方法错误添加了@Autowired注解,该方法是WebSecurityConfigurerAdapter提供的可重写配置方法,不需要也不能加@Autowired,加了之后Spring不会把它识别为安全认证配置的重写方法,导致你配置的userDetailsService没有正确注册到AuthenticationProvider中。 - 你配置
auth.userDetailsService(userDetailsService)的时候没有关联你声明的PasswordEncoderBean,导致认证流程找不到对应的密码处理器,无法完成认证Provider的初始化。
修复方案
第一步:修改AppSecureConfig的认证配置代码
去掉错误的@Autowired注解,添加@Override注解,同时给userDetailsService绑定PasswordEncoder,修改后的代码如下:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @EnableWebSecurity public class AppSecureConfig extends WebSecurityConfigurerAdapter { @Autowired UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService) .passwordEncoder(getPasswordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/user").hasRole("USER") .antMatchers("/").permitAll() .and().formLogin() .and().logout().permitAll(); } @Bean public PasswordEncoder getPasswordEncoder() { return NoOpPasswordEncoder.getInstance(); } }
第二步:可选规范优化
你的自定义类名不符合Java命名规范,虽然不影响运行,但建议修改:
MyuserDetails建议改成MyUserDetailsServiceuserPrincipal建议改成UserPrincipal
测试验证
修复后启动项目:
- 访问
http://localhost:8081/可以直接看到Welcome页面 - 访问
http://localhost:8081/user会跳转到登录页,输入任意用户名,密码填pass即可登录成功看到Welcome user页面
注意:示例中使用的
NoOpPasswordEncoder是明文密码处理器,仅适合测试使用,生产环境请替换为BCryptPasswordEncoder等加密编码器。
内容的提问来源于stack exchange,提问作者Yamini
相关产品推荐
相关产品推荐

