Spring API exception causes filter to be executed

47 Views Asked by At

I have a spring boot application, i am using SecurityConfig. I am using web.ignoring().antMatchers to allow certain (/allowed_api) apis to be accessed without going through the authFilter. If /allowed_api does not throw an exception, everything works as expected. I can access /allowed_api without authFilter being invoked.

Problem

The problem is if /allowed_api throws an exception (any exception 404, 500, etc) , then for some reason, authFilter is invoked, and the api throws an authentication failure exception.

How can i make sure authFilter is never invoked for a certain api (/allowed_api)?

@Configuration
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/allowed_api");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterAfter(new AuthFilter(), BasicAuthenticationFilter.class);

    }
}
1

There are 1 best solutions below

1
Farhan Nasim On

By default, Spring Boot delegates error handling to the /error context path: whenever an endpoint throws an error (e.g. /allowed_api in your case), the /error endpoint takes over. As you have relaxed security check for /allowed_api but not for /error, authentication filter kicks in on any error at /allowed_api.

Relaxing security check for /error, just as you did for /allowed_api, should do.