Spring 启动,过滤器不受特定限制 url

Spring Boot, filter is not getting restricted to specific url

在 spring-boot 应用程序中,我创建了几个 API 调用。我只想为少数网址添加过滤器。安全配置如下:

@Configuration
@EnableWebMvc
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.addFilterBefore(authenticationFilter(), BasicAuthenticationFilter.class)
            .authorizeRequests().anyRequest().denyAll();

        http.authorizeRequests().antMatchers("/api/user").permitAll();

    }

    AuthenticationFilter authenticationFilter() throws Exception
    {
        AuthenticationFilter filter = new AuthenticationFilter();
        return filter;
    }
}

我不希望过滤器应用于除 /api/user 之外的任何 api 调用,因此我拒绝了所有网址并允许 /api/user.

AuthorizationFilter class如下:

public class AuthenticationFilter extends OncePerRequestFilter
{

    public AuthenticationFilter()
    {
        super();
    }

    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException
    {
        Enumeration<String> headerNames = request.getHeaderNames();
        while(headerNames.hasMoreElements()){
            String headerName = headerNames.nextElement();
            System.out.println("headerName " + headerName);
            System.out.println("headerVal " + request.getHeader(headerName));
        }
        chain.doFilter(request,response);
    }
}

这只是打印所有 header 信息。目前它正在打印所有 api 调用的 header 信息,但我希望仅在 /api/user 的情况下打印此信息,而不是在任何其他 api 调用上打印。请建议我应该做哪些修改?

找到了可行的解决方案

@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/api/**");
        // add security constraints for /api/... here
    }

    /* rest of config */
}