I\'m trying to use JavaConfig instead of XML configuration for Spring Security.
I would like to use @PreAuthorization
for declaring access rights.
My Sp
In my case, I have a line super.configure(auth);
in the overriding method configure(AuthenticationManagerBuilder auth)
.
After it was removed, the exception is gone.
from the stacktrace, you don't have authentication manager defiend correctly :
Caused by: java.lang.IllegalArgumentException: Expecting to only find a single bean for type interface org.springframework.security.authentication.AuthenticationManager, but found []
Here is working example :
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
Just add the global method annotation, and change to method to not override and be autowired.
According to your stacktrace, there’s no AuthenticationManager
bean in your context.
Expecting to only find a single bean for type interface org.springframework.security.authentication.AuthenticationManager, but found []
It seems that you need to explicitly expose AuthenticationManager
as a bean; try this:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser( "user" ).password( "password" ).roles( "USER" );
}
@Bean @Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
As NimChimpsky notes, Spring 3.2.0.RELEASE requires a configuration update.
Using this configuration, I was getting exactly the same exception as the OP, but only about half the time. The other half of the time the app started up just fine. I assume that there's some kind of race condition.
Originally I was pulling the security configuration in using @Import
on my root configuration:
@Configuration
@Import(SecurityConfig.class)
... other annotations ...
public class RootConfig {
...
}
When I replaced that with
public class WebAppInit extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class, SecurityConfig.class };
}
}
the problem went away. Didn't dive into the reasons why, so I can't speak to that, but you might give it a try.