3

I have a Spring Boot applicaton, in which I am trying to create a custom security filter like below:

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

Now, I want to invoke this only on a specific URL, but I am not able to figure this out. I am invoking it using below code:

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

Now, I could see that this filter gets added to right place in Spring Security filter chain but it gets invoked on every request. I don't want that and also I want to invoke this filter only on specific URL.

I have gone through guide provided by spring and many articles. But I am still not successful on this. Any guidance would be appreciated.

dur
  • 13,039
  • 20
  • 66
  • 96
Onki
  • 1,507
  • 1
  • 28
  • 50
  • Your configuration should only be applied for URL `/needCustomSecurityOnThisURL`. Did you expose your `CustomSecurityFilter` as a bean? – dur Jul 26 '19 at 19:30

1 Answers1

8

Once I used this:

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

}

}

S.Step
  • 371
  • 2
  • 7