我正在配置 Spring Security。为了验证和授权用户,我覆盖了 configure(AuthenticationManagerBuilder auth)的 WebSecurityConfigurerAdapter .这工作正常。下面是我的代码:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(customUserDetailsService)
.passwordEncoder(getPasswordEncoder());
}
但是当我尝试启用方法级别的安全性时,每个操作,使用
@EnableGlobalMethodSecurity(securedEnabled = true)它抛出一个异常:
No AuthenticationManager found
据我了解
AuthenticationManager用于验证和授权用户,我已经在使用
configure(AuthenticationManagerBuilder auth)和 Spring 正在注入(inject)
auth对象本身。
为什么我需要注册
AuthenticationManager手动?
@Bean @Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
有什么不同的用途
configure(AuthenticationManagerBuilder auth)和
authenticationManagerBean()供应?
我正在扩展
WebSecurityConfigurerAdapter .为什么我需要提供自定义
AuthenticationManager通过覆盖
authenticationManagerBean() .
请您参考如下方法:
您的配置类扩展 WebSecurityConfigurerAdapter ,它只配置网络安全(不是方法安全):
Provides a convenient base class for creating a
WebSecurityConfigurerinstance. The implementation allows customization by overriding methods.
所以你的
AuthenticationManager仅用于网络安全。
如果要配置(更改默认值)方法安全性,可以扩展
GlobalMethodSecurityConfiguration :
Base
Configurationfor enabling global method security. Classes may extend this class to customize the defaults, but must be sure to specify theEnableGlobalMethodSecurityannotation on the subclass.
配置
AuthenticationManager为了方法安全,您可以
GlobalMethodSecurityConfiguration#configure :Sub classes can override this method to register different types of authentication. If not overridden,
configure(AuthenticationManagerBuilder)will attempt to autowire by type.
AuthenticationManager作为可以由 GlobalMethodSecurityConfiguration Autowiring 的 bean ,见 WebSecurityConfigurerAdapter#authenticationManagerBean :Override this method to expose the
AuthenticationManagerfromconfigure(AuthenticationManagerBuilder)to be exposed as a Bean.
AuthenticationManager通过 Autowiring 全局 AuthenticationManagerBuild ,见 Spring Security 3.2.0.RC2 Released :For example, if you want to configure global authentication (i.e. you only have a single AuthenticationManager) you should autowire the AuthenticationMangerBuilder:
@Autowired public void configureGlobal(AuthenticationManagerBuilder auth) { // ... configure it ... }




