gpt4 book ai didi

Spring 安全 : configure(AuthenticationManagerBuilder auth) vs authenticationManagerBean()

转载 作者:行者123 更新时间:2023-12-04 14:55:32 28 4
gpt4 key购买 nike

我正在配置 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 WebSecurityConfigurer instance. The implementation allows customization by overriding methods.


所以你的 AuthenticationManager仅用于网络安全。
如果要配置(更改默认值)方法安全性,可以扩展 GlobalMethodSecurityConfiguration :

Base Configuration for enabling global method security. Classes may extend this class to customize the defaults, but must be sure to specify the EnableGlobalMethodSecurity annotation 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 AuthenticationManager from configure(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 ...
    }

  • 关于 Spring 安全 : configure(AuthenticationManagerBuilder auth) vs authenticationManagerBean(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42316643/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com