What is implication of adding @Component to custom Spring Security filter

╄→гoц情女王★ 提交于 2019-12-07 04:21:35

问题


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
        }
    }
}

回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!