Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security exclude URL on custom filter

@SuppressWarnings("SpringJavaAutowiringInspection")
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

   @Autowired
   private JwtAuthenticationEntryPoint unauthorizedHandler;

   @Autowired
   private UserDetailsService userDetailsService;

   @Autowired
   public void configureAuthentication(AuthenticationManagerBuilder
      authenticationManagerBuilder) throws Exception {
      authenticationManagerBuilder.userDetailsService(userDetailsService);
   }

   @Bean
   public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
      return new JwtAuthenticationTokenFilter();
   }

   @Override
   protected void configure(HttpSecurity httpSecurity) throws Exception {
      httpSecurity
         .csrf().disable()
         .exceptionHandling()
             .authenticationEntryPoint(unauthorizedHandler)
             .and()
         .sessionManagement()
             .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
             .and()
         .authorizeRequests()
             .antMatchers("/test").permitAll()
             .antMatchers("/api/**").permitAll()
             .anyRequest().authenticated();

      httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
   }
}

I have a custom filter that runs before Spring Security. I want to be able to exclude some URLs (like /test) from the filter and Spring Security and others to be intercepted (like /api/**).

When using postman to test localhost/test it still goes through the filter even though I have antMatchers("/test").permitAll().

How do I bypass the filter?

like image 360
techRunner Avatar asked Nov 07 '16 22:11

techRunner


1 Answers

You can disable the Spring Security filter chain for some URLs, see WebSecurity#ignoring:

Allows adding RequestMatcher instances that should that Spring Security should ignore. Web Security provided by Spring Security (including the SecurityContext) will not be available on HttpServletRequest that match. Typically the requests that are registered should be that of only static resources. For requests that are dynamic, consider mapping the request to allow all users instead.

Example Usage:

webSecurityBuilder.ignoring()
// ignore all URLs that start with /resources/ or /static/
               .antMatchers("/resources/**", "/static/**");

Therefore, you can override WebSecurityConfigurerAdapter#configure:

Override this method to configure WebSecurity. For example, if you wish to ignore certain requests.

To ignore path /test you have to add following method to your configuration:

public void configure​(WebSecurity web)
    webSecurityBuilder
        .ignoring()
            .antMatchers("/test");
}
like image 182
dur Avatar answered Oct 14 '22 04:10

dur