【问题标题】:Configure two spring security filters based on path根据路径配置两个spring安全过滤器
【发布时间】:2022-08-05 01:35:34
【问题描述】:

在我的应用程序中,有两个根据路径生效的身份验证选项。 API 路径下的所有端点都通过一个简单的令牌进行身份验证。所有其他人通过 OAuth2。

过去,我有两个类都扩展了 WebSecurityConfigurerAdapter。类似于 https://stackoverflow.com/a/60283968 的类的缩短版本:

@Configuration
@EnableWebSecurity
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ApiEndpointConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .requestMatchers().antMatchers(API + \"/**\")
      .and()
      // authentication for token based authentication
      .authenticationProvider(tokenAuthProvider)
      .addFilterBefore(tokenAuthFilter, BasicAuthenticationFilter.class);
  }
}
@Configuration
@EnableWebSecurity
public class OAuth2EndpointConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http // all non api requests handled here
      .oauth2Login()
      .tokenEndpoint().accessTokenResponseClient(oAuth2AccessTokenResponseClient())
      .and()
      .userInfoEndpoint().userService(oAuth2UserService());
  }
}

在 Spring Security 5.7.0-M2 中,WebSecurityConfigurerAdapter 已被弃用。因此,我现在想用基于组件的配置替换此配置。如此处推荐:https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter。这是我目前失败的地方。

简单地用 SecurityFilterChain 的配置 bean 替换现有方法会导致重复。

@Bean
protected SecurityFilterChain configure(HttpSecurity http) throws Exception {
  return http [...] .build();
}

The bean \'configure\' [...] could not be registered. A bean with that name has already been defined [...]

通过更改注释,我最多只能使一种配置生效。我无法合并配置,因为它们有非常不同的策略。弃用适配器后,如何按路径配置两个不同的过滤器?

    标签: java spring-boot spring-security


    【解决方案1】:

    您不必为两个 bean 保留相同的方法名称“configure”。允许任何自定义方法名称,返回类型“SecurityFilterChain”需要相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-16
      • 1970-01-01
      • 1970-01-01
      • 2017-02-03
      • 2015-04-01
      • 2016-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多