Different filters for different url patterns

Viewed 11081

I have a spring boot application that provides mainly REST endpoints, authentication is done via token (sent in Authorization header) where I have my own TokenAuthenticationFilter added before LogoutFilter to set the security context.

In the process of creating an admin console, I want admin authentication to be separate from regular users, as I'm not sharing tables between Admins and Users for several reasons, on the database level I have the following user,user_token,admin,admin_token. So in order to accomplish this, I thought of several solutions:

  1. Let the current TokenAuthenticationFilter handle user/admin token auth. This however will require to either: Modify the filter to determine whether it's an admin or a user token based on url pattern (so for example if it's /admin/**, the filter will know which service to call) or have the admins header unique from the users (i.e. User sends U-Auth header, Admin sends A-Auth header) and the filter will act based on header name. This all doesn't sound good to me.
  2. Specify a set of filters to apply per url pattern, for example /admin/** will have AdminTokenAuthFilter added to the chain, while any other pattern will have the old TokenAuthenticationFilter in the chain. This sounds better than the earlier approach but I'm having trouble to implement it. I tried to register my own FilterRegistrationBean inside my WebSecurityConfigurerAdapter

Example:

 @Bean
 public FilterRegistrationBean adminFilter(){
     FilterRegistrationBean filterRegBean = new FilterRegistrationBean();
     filterRegBean.setFilter(new AdminTokenAuthFilter());
     List<String> urlPatterns = new ArrayList<>();
     urlPatterns.add("/admin/*");
     filterRegBean.setUrlPatterns(urlPatterns);
     return filterRegBean;
 }

This seems to work but I'm unsure if it's proper practice also I'm concerned about one thing, I found that this adds the filter to the springs originalChain of filters, not to the additionalFilters that seems to apply when adding filters regularly in my WebSecurityConfigurerAdapter using http.addFilterBefore(tokenAuthenticationFilter, LogoutFilter.class). I don't want to alter springs original filter chain, i'd rather have my custom filters in the additional filter chain. Can anyone elaborate on this please?

  1. Create two separate dispatcher servlets and make each one listen to a specific url pattern and I suppose each dispatcherServlet will have its own security configuration.

Can anybody share some knowledge on what's the best approach in such a scenario?

1 Answers
Related