'How to add filter before my another filter in spring-security?

I have two different security configurations for my application. One OAuth2SecurityConfiguration and the other is LdapSecurityConfiguration. In OAuth2SecurityConfiguration I have following security configuration with 2 filteres:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .csrf().disable()
            .exceptionHandling()
            .authenticationEntryPoint(authenticationEntryPoint)
            .and()
                .authorizeRequests()
                .antMatchers(OAUTH_ENDPOINT).permitAll()
                .anyRequest().authenticated()
            .and()
                .logout()
                .logoutUrl(LOGOUT_ENDPOINT)
                .logoutSuccessUrl("/")
                .addLogoutHandler(oAuthLogoutHandler)
            .and()
                .addFilterAfter(oAuth2ClientContextFilter, ExceptionTranslationFilter.class)
                .addFilterBefore(oAuth2AuthenticationProcessingFilter, FilterSecurityInterceptor.class)
                // anonymous login must be disabled,
                // otherwise an anonymous authentication will be created,
                // and the UserRedirectRequiredException will not be thrown,
                // and the user will not be redirected to the authorization server
                .anonymous().disable();
}

LdapSecurityConfiguration security configuration:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .csrf().disable()
            .exceptionHandling()
            .authenticationEntryPoint(restAuthenticationEntryPoint)
            .and()
                .authorizeRequests()
                .antMatchers(AUTH_ENDPOINT).permitAll()
                .anyRequest().authenticated()
            .and()
                .logout()
            .and()
                .addFilterBefore(authenticationFilter, OAuth2ClientContextFilter.class);
}

But when filter chain is initialised I get this error:

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Cannot register after unregistered Filter class org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 36 more
Caused by: java.lang.IllegalArgumentException: Cannot register after unregistered Filter class org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter
    at org.springframework.security.config.annotation.web.builders.FilterComparator.registerBefore(FilterComparator.java:183)
    at org.springframework.security.config.annotation.web.builders.HttpSecurity.addFilterBefore(HttpSecurity.java:1039)
    at com.company.configuration.LdapSecurityConfiguration.configure(LdapSecurityConfiguration.java:63)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:224)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:315)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:86)
    at com.company.configuration.LdapSecurityConfiguration$$EnhancerBySpringCGLIB$$b4922dd5.init(<generated>)
    at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:371)
    at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:325)
    at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:104)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$33ca6b4e.CGLIB$springSecurityFilterChain$3(<generated>)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$33ca6b4e$$FastClassBySpringCGLIB$$b8c23686.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$33ca6b4e.springSecurityFilterChain(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 37 more


Solution 1:[1]

How to add filter before my another filter in spring-security?

with addFilterBefore

Cannot register after unregistered Filter

but only if the one you're trying to add it before is actually there

The problem is you have two separate configurations. You need to make sure they're applied in the correct order (with Ordered or @Order), or just merge them into a single configuration.

Note also that your configurations are trying to configure logout() and exceptionHandling() differently. You can't have it both ways like that.

Solution 2:[2]

The answer helped me : https://stackoverflow.com/a/32227901/1110253. I "wrap" OAuth2AuthenticationProcessingFilter with custom filter.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 OrangeDog
Solution 2 SparX