0

I want to secure only few specific endpoints and if any request comes to secured endpoint I want to apply filter on that.
This is what I have tried as of now:

http
    .csrf().disable()
    .addFilterAfter((Filter) MyFilter, UsernamePasswordAuthenticationFilter.class)
    .authorizeRequests()
          .antMatchers("/api/users").permitAll()
          .anyRequest().authenticated();

I am expecting that it should secure only /api/users and if any request comes to this secured endpoint, then it should go through the filter. But right now each request is going through the filter.
Please suggest what is the right way to do this.

dur
  • 15,689
  • 25
  • 79
  • 125
ngi
  • 51
  • 5
  • *I am expecting that it should secure only /api/users and if any request comes to this secured endpoint, then it should go through the filter.* This is wrong, the filter is always applied to all URLs in the filter chain. There are several ways to exclude one URL for the filter. The most one is to implement it in the filter. – dur Dec 21 '22 at 20:31

1 Answers1

1

Create a RequestMatcher in your Filter and make it only apply to requests that match.

public class MyFilter implements Filter {

  private RequestMatcher requestMatcher = new AntPathRequestMatcher("/api/users");

  @Override
  public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {
      if (!this.requestMatcher.matches(request)) {
        // the request do not match, do nothing but continue the filter chain
        chain.doFilter(request, response);
        return;
      }
      // do the filter logic
  }

}