Search code examples
spring-bootspring-securityspring-boot-security

How to secure specific URL with filter?


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.


Solution

  • 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
      }
    
    }