Я пытаюсь добавить защиту метода в мое приложение Spring MVC.Spring Security 4 Требуется менеджер аутентификации
Я использую Spring: 4.2.3 Spring-Security 4.0.3
Проблема заключается в том, что я получаю ошибку
Caused by: java.lang.IllegalArgumentException: An AuthenticationManager is required
Однако, когда я добавить
@Bean
@Override
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManagerBean();
}
к моему SecurityConfiguration extends WebSecurityConfigurerAdapter
Я получаю следующую ошибку:
Caused by: java.lang.IllegalStateException: Cannot apply org.springframework.security.config.annotation.aut[email protected]43744ca2 to already built object
Вот мой полный SecurityConfiguration:
@Configuration
@EnableWebSecurity
@ComponentScan
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
OntoRAISUserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.
formLogin().
and().
logout().
and().
authorizeRequests().
// antMatchers("/api/search/users/all").permitAll().
antMatchers("/login").permitAll().
anyRequest().authenticated().
and().csrf().disable();
}
@Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder encoder = passwordEncoder();
auth
.userDetailsService(userDetailsService)
.passwordEncoder(encoder);
}
@Bean
@Override
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManagerBean();
}
private BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
public OntoRAISUserDetailsService getUserDetailsService() {
return userDetailsService;
}
public void setUserDetailsService(OntoRAISUserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
}
MethodSecurityConfiguration
В настоящее время мой пуст.
UPDATE: Я посмотрел дальше в StackTrace, и обнаружил, что первоначальное исключение было больше информации, которая могла бы быть полезной. Так вот:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: OntoRais.security.OntoRAISUserDetailsService OntoRais.config.SecurityConfiguration.userDetailsService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ontoRAISUserDetailsService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private OntoRais.datalayer.ontology.service.UserService OntoRais.security.OntoRAISUserDetailsService.userService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService' defined in file [/home/bwright/Repositories/ontology-toolchain/OntoRais/target/OntoRais/WEB-INF/classes/OntoRais/datalayer/ontology/service/UserService.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Unexpected AOP exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'methodSecurityInterceptor' defined in class path resource [OntoRais/config/MethodSecurityConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: An AuthenticationManager is required
Я не привык к @Autowired на метод configure (...) - работает ли это (т. е. активируется ли этот способ)? Документы [docs] (http://docs.spring.io/spring-security/site/docs/current/apidocs/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurerAdapter.html#authenticationManager) показывают, что Менеджер Auth будет настроен, если вызывается этот метод configure (...). –
Хорошо сделал короткий тест о методе configure: Я заменил '@ Autowired' на' @ Override' и никакой аннотации: все с тем же результатом, что я получил вышеприведенную ошибку. Однако я также заметил, что когда я добавил system.out в начале метода, что метод не был вызван – bwright