I have a custom Spring Security filter extending GenericFilterBean.
To do automatic dependency and bean creation I added a @Component annotation.
In my Security config I also register the filter like:
@Autowired
private RestAuthenticationFilter restAuthenticationFilter;
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.addFilterBefore(restAuthenticationFilter, LogoutFilter.class)
Everything works well except that my filter is called twice... It seems Spring adds filters also automatically to standard filters.
What should be the best approach here?
UPDATE
@Dave is this what you mean? It seems to work.
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application extends WebMvcConfigurerAdapter {
@Autowired
private RestAuthenticationFilter restAuthenticationFilter;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public ApplicationSecurity applicationSecurity() {
return new ApplicationSecurity();
}
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setEnabled(false);
filterRegistrationBean.setFilter(restAuthenticationFilter);
return filterRegistrationBean;
}
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter {
@Autowired
private RestAuthenticationFilter restAuthenticationFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.addFilterBefore(restAuthenticationFilter, LogoutFilter.class)
.authorizeRequests()
.anyRequest().authenticated()
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(new Http403ForbiddenEntryPoint())
.and()
.requestCache()
.requestCache(new NullRequestCache())
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// @formatter:on
}
}
}
You need to explicitly register the filter and mark it as "enabled=false" using the FilterRegistrationBean
API. Then Spring Security will use it in its chain, but Boot will not try and register it as well.
来源:https://stackoverflow.com/questions/24381191/what-is-implication-of-adding-component-to-custom-spring-security-filter