Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke a filter before spring security filter chain in boot

Tags:

spring-boot

I have configured my filter as below but it doesn't get invoked before Spring Security Filter chain. I have set the order as zero

I'm using Spring Boot 1.3 which support setting order on filter

@Bean
public FilterRegistrationBean filterRegistrationBean() {

  FilterRegistrationBean registrationBean = new FilterRegistrationBean();

  registrationBean.setFilter(new UrlRewriteFilter());
  registrationBean.addUrlPatterns("*");
  registrationBean.addInitParameter("confReloadCheckInterval", "5");
  registrationBean.addInitParameter("logLevel", "DEBUG");
  registrationBean.addInitParameter("confPath", "urlrewrite.xml");
  registrationBean.setOrder(0);

  return registrationBean;
}
like image 294
Deepak Parmar Avatar asked Dec 11 '15 18:12

Deepak Parmar


2 Answers

application.properties

security.filter-order=5
//>spring 2.1.3
spring.security.filter-order=5

These properties change from time to time and can be found here

https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#actuator-properties

I haven't done this myself but looking at the code it appears you simply need to set a property for the order of the security filter. For example in application.properties

This should order your filter before the security filter. I don't know what the implications are of changing this order as far as security goes it feels a bit risky to me. There is a discussion amongst the Spring developers about this here. It ends up in them implementing what my answer was above.

Discussion

https://github.com/spring-projects/spring-boot/issues/1640

Test showing what this property does.(search for testCustomFilterOrder())

https://github.com/spring-projects/spring-boot/blob/1.2.x/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityAutoConfigurationTests.java

like image 97
Zergleb Avatar answered Mar 03 '23 14:03

Zergleb


The best way I have found to do this in SpringBoot 2.0 is in your Spring Security Configuration using addFilterBefore. I chose to do it before the Username Password filter as my filter was an alternative login filter

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(new UrlRewriteFilter(), UsernamePasswordAuthenticationFilter.class)
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/*/**").permitAll()
            .antMatchers("/api/login").permitAll()
            .antMatchers("/api/**").access("hasRole('ROLE_ADMIN')");
    }
}
like image 25
sparkdoo Avatar answered Mar 03 '23 13:03

sparkdoo