Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking a custom Spring Security filter only on specific URL

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.

like image 369
Onki Avatar asked Oct 18 '25 13:10

Onki


1 Answers

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

}

}

like image 98
S.Step Avatar answered Oct 21 '25 03:10

S.Step