9

I am using spring-security-oauth2 in IDP mode and spring-boot. I need to do some work before the oauth token is extracted from the request. How do I add a filter before OAuth2AuthenticationProcessingFilter?

I have tried:

@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfigurerAdapter extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().anyRequest().authenticated().and()
                .addFilterBefore(new MyFilter(), OAuth2AuthenticationProcessingFilter.class);
    }

}

But I get the following exception:

java.lang.IllegalArgumentException: Cannot register after unregistered Filter class org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter

I guess this might be because @EnableResourceServer is executed after configure(HttpSecurity http).

jax
  • 37,735
  • 57
  • 182
  • 278
  • Could you add any `interceptor` instead of `filter` ? – Ataur Rahman Munna Oct 18 '17 at 04:30
  • I am using these filters in multiple WebSecurityConfigs. As long as Interceptors allow this I should be able to use them. I also need to control the order in which the filter runs (TenantFilter runs before JwtFilter which in turn runs before WebAsyncManagerIntegrationFilter etc.). I also need to be able to selectively use different Interceptors for different WebSecurityConfigs. Is this possible with Interceptors? Can you provide an example? – jax Oct 18 '17 at 05:21
  • This may be help for you. https://stackoverflow.com/q/11586757/4423636 – Ataur Rahman Munna Oct 18 '17 at 06:36
  • 1
    @jax Did you solve this? I have the exact same problem, and it only ends up with anti-patterns and ugly stuff :( I'd like to be able to add a filter, once the filterchain has been created by `@EnableResourceServer`. – sjahan Nov 06 '18 at 16:52
  • @jax Have you resolve the issue? – user3123690 Jan 19 '19 at 00:38

2 Answers2

5

I achieved desired functional by doing this

                .addFilterBefore(new MyTokenFilter(), AbstractPreAuthenticatedProcessingFilter.class)
Olegdelone
  • 189
  • 4
  • 15
1

The following worked for me

   @Override
   public void configure(HttpSecurity http) throws Exception {
       http
         .addFilterBefore(new MyFilter(), AbstractPreAuthenticatedProcessingFilter.class)
         .authorizeRequests().anyRequest().fullyAuthenticated()
       ;
   }

Result

Security filter chain: [
  WebAsyncManagerIntegrationFilter
  SecurityContextPersistenceFilter
  HeaderWriterFilter
  LogoutFilter
  MyFilter
  OAuth2AuthenticationProcessingFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  SessionManagementFilter
  ExceptionTranslationFilter
  FilterSecurityInterceptor
]