【问题标题】:Invoking a custom Spring Security filter only on specific URL仅在特定 URL 上调用自定义 Spring Security 过滤器
【发布时间】:2019-12-04 10:54:49
【问题描述】:

我有一个 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提供的指南和许多文章。但我在这方面仍然没有成功。任何指导将不胜感激。

【问题讨论】:

  • 您的配置只能应用于 URL /needCustomSecurityOnThisURL。您是否将您的 CustomSecurityFilter 暴露为 bean?

标签: java spring spring-security restful-authentication spring-filter


【解决方案1】:

我用过这个:

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

}

}

【讨论】:

  • 为我工作。也可以用于否定,以排除某些端点。
猜你喜欢
  • 2011-08-23
  • 2014-07-28
  • 2013-07-22
  • 1970-01-01
  • 2016-04-26
  • 2011-04-26
  • 2014-10-24
  • 1970-01-01
  • 2017-05-08
相关资源
最近更新 更多