我正在尝试通过Spring Boot实施一个用于弹簧安全性的示例演示,以检查身份验证。我正在尝试实施一项针对弹簧安全性的基本锻炼,并获得以下消息,
Description:
Parameter 0 of constructor in com.spacestudy.service.CustomAuthenticationProvider required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.security.web.AuthenticationEntryPoint' in your configuration.
我的安全性配置类SecurityConfig.java,
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationEntryPoint authEntryPoint;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.addFilter(new ApplicationContextHeaderFilter((ApplicationContext) authenticationManager()));
}
}
以及我的BasicAuthenticationFilter实现,如下所示
@Component
public class CustomAuthenticationProvider extends BasicAuthenticationFilter {
public CustomAuthenticationProvider(AuthenticationManager authenticationManager) {
super(authenticationManager);
// TODO Auto-generated constructor stub
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(request, response);
}
private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
String bearerToken = request.getHeader("accessToken");
String username = "test";
String password = "test";
if (username != null && !username.isEmpty()) {
return new UsernamePasswordAuthenticationToken(username, null, null);
}
return null;
}
}
如果我在此方向错误,有人可以指导我解决此问题吗?
[我不确定,但不应CustomAuthenticationProvider implement AuthenticationProvider
和AuthenticationManager
只是用于身份验证提供程序的容器,似乎您没有任何容器。
查看更多信息,请访问此网站https://www.baeldung.com/spring-security-authentication-provider
您的错误似乎是AuthenticationManager
不作为Spring Bean出现。
在Spring Bean中注册AuthenticationManager
。 Spring提供的所有功能都可以直接在您的SecurityConfig
类中通过覆盖WebSecurityConfigurerAdapter#authenticationManagerBean
方法(如其documentation中的解释]来做到这一点
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
[避免在Spring中注册AuthenticationManager
,但直接注册CustomAuthenticationProvider
类。
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public CustomAuthenticationProvider authenticationProvider() throws Exception {
return new CustomAuthenticationProvider(authenticationManager());
}
}
请不要忘记使用此方法删除@Component
类上的CustomAuthenticationProvider
注释。