仅对少数路径禁用过滤器

RMS*_*MSD 1 java spring spring-security spring-boot springfox

如何获取过滤器以应用于根路径之外的每个请求(我想忽略的请求除外)?这是我的例子:

我有一个 Spring Security 过滤器,如下所示:

private static class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .antMatcher("/**")
            .addFilterBefore(new AuthenticationFilter(), basicAuthenticationFilter.class);
    }

    @Override
    public void configure(WebSecurity web) {
        web
           .ignoring()
               .requestMatchers(SecurityServletRequestMatchers.servletIgnoreAuthMatcher());
    }
}
Run Code Online (Sandbox Code Playgroud)

该过滤器填充一个CustomApiToken包含所有标头信息的对象,并将其放入 Spring Security 上下文中SecurityContextHolder.getContext().setAuthentication(token),以便轻松访问请求控制器上的令牌。

我正在尝试将 Springfox 添加到项目中,这意味着我想禁用 UI 和 API 文档页面的过滤器。

我最初的尝试是在该方法中添加一个子句:

@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .antMatcher("/**")
        .addFilterBefore(new AuthenticationFilter(), BasicAuthenticationFilter.class);

    http
        .requestMatcher(SecurityServletRequestMatchers.servletIgnoreAuthMatcher())
        .headers() //.servletIgnoreAuthMatchers has all the swagger urls also
            .defaultsDisabled()
            .disable()
        .authorizeRequests()
            .anyRequest().authenticated();
}
Run Code Online (Sandbox Code Playgroud)

但是我发现这只考虑了第二个子句,因为 Spring Security 只接受最后一个子句。

从那以后我尝试过:

@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .antMatcher("/**")
        .addFilterBefore(new AuthenticationFilter(), BasicAuthenticationFilter.class)
        .requestMatcher(SecurityServletRequestMatchers.servletIgnoreAuthMatcher())
        .headers()
            .defaultsDisabled()
            .disable()
        .authorizeRequests()
            .anyRequest().authenticated();
}
Run Code Online (Sandbox Code Playgroud)

但这使得 Springfox URL 上的 Web 过滤器给我一个缺少身份验证令牌的错误。

我尝试在这里和互联网上查找,但没有一个例子给我一个可以接受的回应。

Mar*_*gio 6

在您的自定义中,AuthenticationFilter您可以定义 aRequestMatcher并在执行逻辑之前使用它,如下所示:

public class AuthenticationFilter extends OncePerRequestFilter {
    private final RequestMatcher ignoredPaths = new AntPathRequestMatcher("/swagger-ui");

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
        if (this.ignoredPaths.matches(request)) { 
             filterChain.doFilter(request, response);
             return;
        }

        // do your logic
        filterChain.doFilter(request, response);
    }
}
Run Code Online (Sandbox Code Playgroud)