spring_reference/IX. ‘How-to’ guides/71.2. Change the Authentica...

34 lines
1.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

### 71.2. 改变AuthenticationManager并添加用户账号
如果你提供了一个AuthenticationManager类型的`@Bean`那么默认的就不会被创建了所以你可以获得Spring Security可用的全部特性比如[不同的认证选项](http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#jc-authentication))。
Spring Security也提供了一个方便的AuthenticationManagerBuilder可用于构建具有常见选项的AuthenticationManager。在一个webapp中推荐将它注入到WebSecurityConfigurerAdapter的一个void方法中比如
```java
@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
}
```
如果把它放到一个内部类或一个单独的类中,你将得到最好的结果(也就是不跟很多其他`@Beans`混合在一起将允许你改变实例化的顺序)。[secure web sample](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-web-secure)是一个有用的参考模板。
如果你遇到了实例化问题比如使用JDBC或JPA进行用户详细信息的存储那将AuthenticationManagerBuilder回调提取到一个GlobalAuthenticationConfigurerAdapter放到init()方法内以防其他地方也需要authentication manager可能是个不错的选择比如
```java
@Configuration
public class AuthenticationManagerConfiguration extends
GlobalAuthenticationConfigurerAdapter {
@Override
public void init(AuthenticationManagerBuilder auth) {
auth.inMemoryAuthentication() // ... etc.
}
}
```