78.2 Change the AuthenticationManager and add user accounts
If you provide a @Bean of type AuthenticationManager the default one will not be created, so you have the full feature set of Spring Security available (e.g. various authentication options).
Spring Security also provides a convenient AuthenticationManagerBuilder which can be used to build an AuthenticationManager with common options. The recommended way to use this in a webapp is to inject it into a void method in a WebSecurityConfigurerAdapter, e.g.
_@Configuration_
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
_@Autowired_
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("barry").password("password").roles("USER"); // ... etc.
}
// ... other stuff for application security
}
You will get the best results if you put this in a nested class, or a standalone class (i.e. not mixed in with a lot of other @Beans that might be allowed to influence the order of instantiation). The secure web sample is a useful template to follow.
If you experience instantiation issues (e.g. using JDBC or JPA for the user detail store) it might be worth extracting the AuthenticationManagerBuilder callback into a GlobalAuthenticationConfigurerAdapter (in the init() method so it happens before the authentication manager is needed elsewhere), e.g.
_@Configuration_
public class AuthenticationManagerConfiguration extends
GlobalAuthenticationConfigurerAdapter {
_@Override_
public void init(AuthenticationManagerBuilder auth) {
auth.inMemoryAuthentication() // ... etc.
}
}