Spring Security:配置(AuthenticationManagerBuilder auth)与 authenticationManagerBean()

Posted

技术标签:

【中文标题】Spring Security:配置(AuthenticationManagerBuilder auth)与 authenticationManagerBean()【英文标题】:Spring Security : configure(AuthenticationManagerBuilder auth) vs authenticationManagerBean() 【发布时间】:2017-07-08 02:01:27 【问题描述】:

我正在配置 Spring Security。为了验证和授权用户,我覆盖了WebSecurityConfigurerAdapterconfigure(AuthenticationManagerBuilder auth)。这工作正常。以下是我的代码:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception 
    auth
        .userDetailsService(customUserDetailsService)
        .passwordEncoder(getPasswordEncoder());

但是当我尝试启用方法级别的安全性时,每个操作,使用 @EnableGlobalMethodSecurity(securedEnabled = true) 它会引发异常:

未找到 AuthenticationManager

据我了解,AuthenticationManager 用于对用户进行身份验证和授权,我已经在使用 configure(AuthenticationManagerBuilder auth) 并且 Spring 正在注入 auth 对象本身。

为什么我需要手动注册AuthenticationManager

@Bean @Override
public AuthenticationManager authenticationManagerBean() throws Exception 
    return super.authenticationManagerBean();

configure(AuthenticationManagerBuilder auth)authenticationManagerBean() 有什么不同的用途?

我正在扩展WebSecurityConfigurerAdapter。为什么我需要通过覆盖authenticationManagerBean() 来提供自定义AuthenticationManager

【问题讨论】:

【参考方案1】:

你的配置类扩展WebSecurityConfigurerAdapter,它只配置网络安全(不是方法安全):

为创建WebSecurityConfigurer 实例提供了一个方便的基类。该实现允许通过覆盖方法进行自定义。

所以您的AuthenticationManager 仅用于网络安全。

如果要配置(更改默认值)方法安全性,可以扩展GlobalMethodSecurityConfiguration

Base Configuration 用于启用全局方法安全性。类可以扩展这个类来自定义默认值,但必须确保在子类上指定EnableGlobalMethodSecurity注解。

要为方法安全配置AuthenticationManager,您可以

    覆盖GlobalMethodSecurityConfiguration#configure

    子类可以重写此方法来注册不同类型的身份验证。如果没有被覆盖,configure(AuthenticationManagerBuilder) 将尝试按类型自动装配。

    将您的AuthenticationManager 公开为可以由GlobalMethodSecurityConfiguration 自动装配的bean,请参阅WebSecurityConfigurerAdapter#authenticationManagerBean

    重写此方法以将 configure(AuthenticationManagerBuilder) 中的 AuthenticationManager 公开为 Bean。

    通过自动装配全局AuthenticationManagerBuild,仅使用一个全局AuthenticationManager,参见Spring Security 3.2.0.RC2 Released:

    例如,如果您想配置全局身份验证(即您只有一个 AuthenticationManager),您应该自动装配 AuthenticationMangerBuilder:

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) 
        // ... configure it ...
    
    

【讨论】:

以上是关于Spring Security:配置(AuthenticationManagerBuilder auth)与 authenticationManagerBean()的主要内容,如果未能解决你的问题,请参考以下文章