【问题标题】:Spring AuthenticationManager and circular dependencySpring AuthenticationManager 和循环依赖
【发布时间】:2021-04-24 17:13:02
【问题描述】:

我的情况是,我需要为单个端点提供两种登录机制。
我已经应用了来自 Using multiple WebSecurityConfigurerAdapter in spring boot 现在遇到了AuthenticationManager 的问题。

AuthenticationManager 存在于WebSecurityConfigurerAdapter 中,在ServiceWebSecurityConfigurer 的实现中是必需的。但是ServiceWebSecurityConfigurer 用于实现WebSecurityConfigurerAdapter,从而形成循环依赖。

@Configuration
@EnableWebSecurity
public class UnitedSecurityConfiguration extends WebSecurityConfigurerAdapter {

  @Autowired
  private List<ServiceWebSecurityConfigurer> serviceWebSecurityConfigurers;

  @Override
  public void configure(HttpSecurity http) {
    serviceWebSecurityConfigurers.forEach(configurer -> configure.config(http));
  }

  @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
  @Override
  public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
  }
}

@Configuration
public class SecurityConfiguration implements ServiceWebSecurityConfigurer {
  @Autowired
  private AuthenticationManager authenticationManager;

  @Bean
  public SAMLWebSSOHoKProcessingFilter samlWebSSOHoKProcessingFilter() throws Exception {
    SAMLWebSSOHoKProcessingFilter samlWebSSOHoKProcessingFilter = new SAMLWebSSOHoKProcessingFilter();

  // AuthenticationManager needed here
    samlWebSSOHoKProcessingFilter.setAuthenticationManager(authenticationManager);
    
    return samlWebSSOHoKProcessingFilter;
  }
}

我怎样才能摆脱这种情况?

【问题讨论】:

  • 你为什么要指定一个没有明显作用的覆盖?
  • authenticationManagerBean() 的覆盖是因为 AuthenticationManager 不是 bean - 因此是 @Bean 注解
  • 如果你使用的是最新的Spring,配置类中对@Autowired字段的需求已经被移除了,我建议你把它去掉。也就是说,您是否尝试过在serviceWebSecurityConfigurersauthenticationManager 上使用@Lazy
  • 我不知道@Lazy - 这是诀窍。如果您添加答案,我会接受它:-) 非常感谢。

标签: java spring


【解决方案1】:

要非常简单地解决您最紧迫的问题,请参考@Lazy 之一;这告诉 Spring 使用惰性代理,它可以解决循环问题。我强烈建议这样做:

@Bean
public SAMLWebSSOHoKProcessingFilter samlWebSSOHoKProcessingFilter(
  @Lazy AuthenticationManager authenticationManager // use parameters instead of fields
) { ... } // don't use unnecessary throws clauses

【讨论】:

    猜你喜欢
    • 2015-07-24
    • 2020-07-15
    • 2017-04-03
    • 2011-03-29
    • 1970-01-01
    • 2018-09-21
    • 2015-05-17
    • 2020-11-18
    • 1970-01-01
    相关资源
    最近更新 更多