spring-boot icon indicating copy to clipboard operation
spring-boot copied to clipboard

Prevent Servlet filter re-registration

Open lukas-krecan opened this issue 6 years ago • 2 comments

We are trying to register two servlet filters implemented by the same class on two different paths with different configuration

    @Bean
    fun authFilter1(): FilterRegistrationBean<*> {
        val filter = BasicAuthFilter("username1", "password1")
        val reg = FilterRegistrationBean(filter)
        reg.addUrlPatterns("/path1")
        return reg
    }

    @Bean
    fun authFilter2(): FilterRegistrationBean<*> {
        val filter = BasicAuthFilter("username2", "password2")
        val reg = FilterRegistrationBean(filter)
        reg.addUrlPatterns("/path2")
        return reg
    }

If we register the filters it like this, Spring Boot uses the filter class name to deduce the filter name and since both filters are implemented by the same class, only one filter is effectively registered which is surprising. Basically it's a silent failure.

I would prefer Spring Boot to throw an exception in such case or event better, generate a unique name for each filter.

Of course, once the user is aware of the issue, it can be simply fixed by explicitly specifying the filter name in FilterRegistrationBean.

lukas-krecan avatar Jan 10 '20 10:01 lukas-krecan

I think it would be better to throw an exception and let the user explicitly provide a name.

mbhave avatar Jan 10 '20 19:01 mbhave

The setName(...) method can be used to set a specific name. We could also look at making the registration class BeanNameAware. It looks like we already check for a null response but currently just log " was not registered (possibly already registered?)"

philwebb avatar Jan 10 '20 20:01 philwebb

The same problem occurs with ServletRegistrationBean.

mhalbritter avatar Jan 19 '23 13:01 mhalbritter

I have something working in https://github.com/mhalbritter/spring-boot/tree/mh/19605

It now uses the name, if that's not set, it uses the bean name. If that's not set, it falls back to the convention based naming.

mhalbritter avatar Jan 19 '23 16:01 mhalbritter

@mhalbritter I like that, but I think we should consider it an enhancement and target it to 3.1. There's the chance that existing users might be depending on the class based convention name.

philwebb avatar Jan 19 '23 18:01 philwebb

Looking at this again, we do log a warning if registration fails. https://github.com/spring-projects/spring-boot/blob/69d6aa418b68435fb2e14e4537d614b66dcc8734/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/DynamicRegistrationBean.java#L109.

Perhaps we should keep things as they are in 2.7 but change that to an exception in 3.1.

philwebb avatar Jan 19 '23 18:01 philwebb

Sounds good. I'll refine the PR and close this issue in favor of the PR https://github.com/spring-projects/spring-boot/pull/33911

mhalbritter avatar Jan 20 '23 08:01 mhalbritter