当我试图用spring security设置SecurityConfigurer时,得到这个错误。
APPLICATION FAILED TO START
Description:
Field authenticationManager in com.springvuegradle.Controller.LoginController required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.springframework.security.authentication.AuthenticationManager' in your configuration.
我已经按照其他答案的建议覆盖了 authenticationManagerBean,但这并没有帮助。欢迎任何建议。我的SecurityConfigurer类如下。
package com.springvuegradle.Security;
import com.springvuegradle.Services.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {
@Autowired
private MyUserDetailsService myUserDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetailsService);
}
/***
* Requires authentication for all endpoints except the /authenticate endpoint.
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/authenticate").permitAll().anyRequest().authenticated();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder(){
//TODO change this to actually hash the password
return NoOpPasswordEncoder.getInstance();
}
}
登录控制器
@RestController
public class LoginController {
@Autowired
private AuthenticationManager authenticationManager;
从代码来看,你似乎是想在LoginController中自动连接SecurityConfigurer。但是在spring security中,不需要自动加载configurer类。另外,正如你所提到的,覆盖 authenticationManagerBean只会提供给你一个AuthenticationManager类型的bean,而不是SecurityConfigurer类型。