0

I have a filter which extends AbstractAuthenticationProcessingFilter.

In security config class I have below,

  @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.addFilterBefore(getMyFilter(), BasicAuthenticationFilter.class);
        http.addFilterAfter(getMyFilter2(), MyFilter.class);
        http.csrf().disable().authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll();
    }

    private MyFilter getMyFilter() {
        return new MyFilter(properties, apiConsumer);
    }

When I invoke an REST endpoint with postman, the doFilter method of MyFilter get hits twice. In both time it has the same requestedSessionId and strippedServletPath in the ServletRequest.

But MyFilter2 which extend GenericFilterBean, only get invoke once.

The order of filter execution is MyFilter.doFilter -> MyFilter2.doFilter -> MyFilter.doFilter

What would be the reason and how can I find the root cause?

dur
  • 15,689
  • 25
  • 79
  • 125
Harshana
  • 7,297
  • 25
  • 99
  • 173
  • 1
    I had defined the MyFilter with @Component annotation. When I remove that annotation, It hits only once – Harshana Sep 04 '16 at 04:53

1 Answers1

0

I am guessing that this behaviour appears only on first request (when basic authentication popup window appears). If so, then this is because basic authentication specification and it's implementation in Spring's BasicAuthenticationFilter.

When you invoke your service for the first time, Spring looks for Authorization header on your request, and if it's not present, it sends response with WWW-Authenticate: Basic header to your browser. When your browser receives this response with that particular header, it shows authentication popup. When you type your user and password your browser makes another request (now with appropriate Authorization header) and now Spring can properly authorize your request.

The problem is that during that whole process Spring is processing filter chain twice (on every request).

You can read more about Basic Authentication here: https://en.wikipedia.org/wiki/Basic_access_authentication

Maciej Marczuk
  • 3,593
  • 29
  • 28