gpt4 book ai didi

java - 如何只为一个特殊路径添加过滤器 WebSecurityConfigurerAdapter

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:44:18 28 4
gpt4 key购买 nike

我们有一个看起来像这样的配置:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

public static final String LOGIN_PATH_EXPRESSION = "/login";
public static final String API_PATH_EXPRESSION = "/api/**/*";
public static final String GLOBAL_PATH_EXPRESSION = "/**/*";

@Autowired
@Qualifier("ssoFilter")
private Filter ssoFilter;

@Autowired
private VerifyingProcessingFilter verifyingProcessingFilter;


@Override
protected void configure(HttpSecurity http) throws Exception {
http
.userDetailsService(username -> new User(username, "", Collections.emptyList()))
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(LOGIN_PATH_EXPRESSION)
.authenticated()
.and()
.httpBasic()
.and()
.authenticationProvider(new SimpleAuthenticationProvider())
.authorizeRequests()
.antMatchers(API_PATH_EXPRESSION).authenticated()
.and()
.addFilterBefore(ssoFilter, BasicAuthenticationFilter.class)
.addFilterAfter(verifyingProcessingFilter, FilteredOAuth2AuthenticationProcessingFilter.class)
.authorizeRequests()
.antMatchers(GLOBAL_PATH_EXPRESSION)
.permitAll()
.and()
.csrf()
.disable();
}

并认识到我们在 /login 调用中的 FilteredOAuth2AuthenticationProcessingFilter 内部结束,并问自己为什么会这样。

目标是让 ssoFilterverifyingProcessingFilter 仅在命中路径为 api/**/* 的端点时应用。

现在我们必须在过滤器内部添加一个 AntMatching 检查,以便它只应用于正确的请求,但我认为应该可以只将它添加到匹配的请求。

有人可以提供一个示例,说明如何将过滤器添加到一个特定的 Ant 匹配路径请求吗?

最佳答案

看起来您不能使用单个配置类来做到这一点。看看这个问题:How to apply spring security filter only on secured endpoints? .

对于这种情况,我认为更好的解决方案是配置多个HttpSecurity。来自 Spring IO documentation :

We can configure multiple HttpSecurity instances just as we can have multiple blocks. The key is to extend the WebSecurityConfigurationAdapter multiple times. For example, the following is an example of having a different configuration for URL’s that start with /api/.

该文档有一个完整的示例,其中包含完成此操作的必要步骤:

  1. Configure Authentication as normal
  2. Create an instance of WebSecurityConfigurerAdapter that contains @Order to specify which WebSecurityConfigurerAdapter should be considered first.
  3. The http.antMatcher states that this HttpSecurity will only be applicable to URLs that start with /api/
  4. Create another instance of WebSecurityConfigurerAdapter. If the URL does not start with /api/ this configuration will be used. This configuration is considered after ApiWebSecurityConfigurationAdapter since it has an @Order value after 1 (no @Order defaults to last).

祝你好运!

关于java - 如何只为一个特殊路径添加过滤器 WebSecurityConfigurerAdapter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45820372/

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