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

Onk*_*nki 3 java spring restful-authentication spring-security spring-filter

我有一个 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我只想在特定的 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

小智 8

一旦我使用了这个:

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);

}
Run Code Online (Sandbox Code Playgroud)

}