78.2 改变AuthenticationManager并添加用户账号

如果你提供了一个AuthenticationManager类型的@Bean,那么默认的就不会被创建了,所以你可以获得Spring Security可用的全部特性(比如,不同的认证选项)。

Spring Security也提供了一个方便的AuthenticationManagerBuilder,用于构建具有常见选项的AuthenticationManager。在一个webapp中,推荐将它注入到WebSecurityConfigurerAdapter的一个void方法中,比如:

  1. @Configuration
  2. public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  3. @Autowired
  4. public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
  5. auth.inMemoryAuthentication()
  6. .withUser("barry").password("password").roles("USER"); // ... etc.
  7. }
  8. // ... other stuff for application security
  9. }

如果把它放到一个内部类或一个单独的类中,你将得到最好的结果(也就是不跟很多其他@Beans混合在一起将允许你改变实例化的顺序)。secure web sample是一个有用的参考模板。

如果你遇到了实例化问题(比如,使用JDBC或JPA进行用户详细信息的存储),那将AuthenticationManagerBuilder回调提取到一个GlobalAuthenticationConfigurerAdapter(放到init()方法内以防其他地方也需要authentication manager)可能是个不错的选择,比如:

  1. @Configuration
  2. public class AuthenticationManagerConfiguration extends
  3. GlobalAuthenticationConfigurerAdapter {
  4. @Override
  5. public void init(AuthenticationManagerBuilder auth) {
  6. auth.inMemoryAuthentication() // ... etc.
  7. }
  8. }