gpt4 book ai didi

java - 仅在特定 URL 上调用自定义 Spring Security 过滤器

转载 作者:行者123 更新时间:2023-12-01 19:36:39 33 4
gpt4 key购买 nike

我有一个 Spring Boot 应用程序,我试图在其中创建一个自定义安全过滤器,如下所示:

public class CustomSecurityFilter extends GenericFilterBean {

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//it should be invoked only for "/needCustomSecurityOnThisURL"
chain.doFilter(request, response);
}
}

现在,我只想在特定的 URL 上调用它,但我无法弄清楚这一点。我使用下面的代码调用它:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {

http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.csrf().disable() // Disable CSRF Token
.httpBasic();

// Disable Session Management
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);

//want to add the Custom Security Filter n it should ne applicable only on selected URL
http
.antMatcher("/needCustomSecurityOnThisURL")
.addFilterAfter(new CustomSecurityFilter(), BasicAuthenticationFilter.class);
}
}

现在,我可以看到这个过滤器被添加到 Spring Security 过滤器链中的正确位置,但它会在每个请求上被调用。我不希望这样,而且我只想仅在特定 URL 上调用此过滤器。

我已经阅读了 spring 提供的指南和许多文章。但我在这方面仍然没有成功。任何指导将不胜感激。

最佳答案

一旦我使用了这个:

public class CustomSecurityFilter extends GenericFilterBean {

RequestMatcher customFilterUrl = new AntPathRequestMatcher("/needCustomSecurityOnThisURL/**");



@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

HttpServletRequest httpServletRequest = (HttpServletRequest) request;

if (customFilterUrl.matches(httpServletRequest)) {
//it should be invoked only for "/needCustomSecurityOnThisURL"
} else {
//"Filter NOT intercepted";
}

chain.doFilter(request, response);

}

}

关于java - 仅在特定 URL 上调用自定义 Spring Security 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57214212/

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