繁体   English   中英

根据路径配置两个 spring 安全过滤器

[英]Configure two spring security filters based on path

在我的应用程序中,有两个根据路径生效的身份验证选项。 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 [...]

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

您不必为两个 bean 保留相同的方法名称“配置”。 允许任何自定义方法名称,返回类型“SecurityFilterChain”需要相同。 请参考https://docs.spring.io/spring-security/reference/5.7.0-M2/servlet/configuration/java.html#_multiple_httpsecurity

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM