Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Security configuration is failed to be initialized in a Servlet 6.0 container #13794

Closed
hantsy opened this issue Sep 12, 2023 · 24 comments
Closed
Assignees
Labels
in: config An issue in spring-security-config type: bug A general bug
Milestone

Comments

@hantsy
Copy link

hantsy commented Sep 12, 2023

Describe the bug
I tried to update my example Spring project to the latest Spring 6.1 and Spring Security 6.2, but it can be not started in Tomcat 10 or Jetty 11 container.

The example project: https://github.com/hantsy/spring6-sandbox/tree/master/mvc-freemarker

To Reproduce

  1. Run docker compose up postgres in the root folder to start a Postgres.
  2. Switch to this project folder, and mvn clean package cargo:run -Ptomcat or mvn clean package cargo:run -Pjetty to run the application on an embeded Tomcat or Jetty.

Expected behavior
NOTICE THIS ---> The original project is working with Spring 6.0.x/Spring Security 6.1.x

Now I got an exception like this.

[INFO] [talledLocalContainer] 2023-09-12 17:10:20,454 WARN  [main] org.springframework.context.support.AbstractApplicationContext: Exception encountered during context initialization -
 cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in org.springframework.security.
config.annotation.web.configuration.WebSecurityConfiguration: Failed to instantiate [jakarta.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception with message: S
ection 4.4 of the Servlet 3.0 specification does not permit this method to be called from a ServletContextListener that was not defined in web.xml, a web-fragment.xml file nor annotate
d with @WebListener
[INFO] [talledLocalContainer] 2023-09-12 17:10:20,459 ERROR [main] org.springframework.web.context.ContextLoader: Context initialization failed
[INFO] [talledLocalContainer] org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in org.springframework.security
.config.annotation.web.configuration.WebSecurityConfiguration: Failed to instantiate [jakarta.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception with message: 
Section 4.4 of the Servlet 3.0 specification does not permit this method to be called from a ServletContextListener that was not defined in web.xml, a web-fragment.xml file nor annotat
ed with @WebListener
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:654)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:488)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:13
36)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1166)        
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:563)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:523)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:312)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:973)
[INFO] [talledLocalContainer]   at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:939)
[INFO] [talledLocalContainer]   at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:608)
[INFO] [talledLocalContainer]   at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:394)
[INFO] [talledLocalContainer]   at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:274)
[INFO] [talledLocalContainer]   at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:102)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4420)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4860)
[INFO] [talledLocalContainer]   at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:171)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:683)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:658)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:713)
[INFO] [talledLocalContainer]   at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:975)
[INFO] [talledLocalContainer]   at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1949)
[INFO] [talledLocalContainer]   at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:572)
[INFO] [talledLocalContainer]   at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317)
[INFO] [talledLocalContainer]   at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
[INFO] [talledLocalContainer]   at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:123)
[INFO] [talledLocalContainer]   at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:776)
[INFO] [talledLocalContainer]   at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:426)
[INFO] [talledLocalContainer]   at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1656)
[INFO] [talledLocalContainer]   at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:309)
[INFO] [talledLocalContainer]   at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:114)
[INFO] [talledLocalContainer]   at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:402)
[INFO] [talledLocalContainer]   at org.apache.catalina.util.LifecycleBase.setState(LifecycleBase.java:345)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:893)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:846)
[INFO] [talledLocalContainer]   at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:171)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1332)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1322)
[INFO] [talledLocalContainer]   at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317)
[INFO] [talledLocalContainer]   at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
[INFO] [talledLocalContainer]   at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:145)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:866)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:241)
[INFO] [talledLocalContainer]   at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:171)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.StandardService.startInternal(StandardService.java:433)
[INFO] [talledLocalContainer]   at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:171)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:918)
[INFO] [talledLocalContainer]   at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:171)
[INFO] [talledLocalContainer]   at org.apache.catalina.startup.Catalina.start(Catalina.java:795)
[INFO] [talledLocalContainer]   at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
[INFO] [talledLocalContainer]   at java.base/java.lang.reflect.Method.invoke(Method.java:580)
[INFO] [talledLocalContainer]   at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:347)
[INFO] [talledLocalContainer]   at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:478)
[INFO] [talledLocalContainer] Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [jakarta.servlet.Filter]: Factory method 'springSecurityFilterChain
' threw exception with message: Section 4.4 of the Servlet 3.0 specification does not permit this method to be called from a ServletContextListener that was not defined in web.xml, a w
eb-fragment.xml file nor annotated with @WebListener
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:171)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:650)
[INFO] [talledLocalContainer]   ... 56 common frames omitted
[INFO] [talledLocalContainer] Caused by: java.lang.UnsupportedOperationException: Section 4.4 of the Servlet 3.0 specification does not permit this method to be called from a ServletCo
ntextListener that was not defined in web.xml, a web-fragment.xml file nor annotated with @WebListener
[INFO] [talledLocalContainer]   at org.apache.catalina.core.StandardContext$NoPluggabilityServletContext.getServletRegistrations(StandardContext.java:6197)
[INFO] [talledLocalContainer]   at org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry.mappableServletRegistrations(AbstractRequestMatcherRegistry.java:21
5)
[INFO] [talledLocalContainer]   at org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry.requestMatchers(AbstractRequestMatcherRegistry.java:199)
[INFO] [talledLocalContainer]   at org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry.requestMatchers(AbstractRequestMatcherRegistry.java:276)
[INFO] [talledLocalContainer]   at com.example.demo.SecurityConfig.lambda$ignoringCustomizer$0(SecurityConfig.java:39)
[INFO] [talledLocalContainer]   at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:119
)
[INFO] [talledLocalContainer]   at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
[INFO] [talledLocalContainer]   at java.base/java.lang.reflect.Method.invoke(Method.java:580)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:139)
[INFO] [talledLocalContainer]   ... 57 common frames omitted
[INFO] [talledLocalContainer] 9月 12, 2023 5:10:20 下午 org.apache.catalina.core.StandardContext listenerStart
[INFO] [talledLocalContainer] SEVERE: Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
[INFO] [talledLocalContainer] org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in org.springframework.security
.config.annotation.web.configuration.WebSecurityConfiguration: Failed to instantiate [jakarta.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception with message: 
Section 4.4 of the Servlet 3.0 specification does not permit this method to be called from a ServletContextListener that was not defined in web.xml, a web-fragment.xml file nor annotat
ed with @WebListener
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:654)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:488)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:13
36)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1166)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:563)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:523)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:312)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:973)
[INFO] [talledLocalContainer]   at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:939)
[INFO] [talledLocalContainer]   at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:608)
[INFO] [talledLocalContainer]   at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:394)
[INFO] [talledLocalContainer]   at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:274)
[INFO] [talledLocalContainer]   at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:102)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4420)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4860)
[INFO] [talledLocalContainer]   at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:171)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:683)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:658)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:713)
[INFO] [talledLocalContainer]   at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:975)
[INFO] [talledLocalContainer]   at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1949)
[INFO] [talledLocalContainer]   at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:572)
[INFO] [talledLocalContainer]   at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317)
[INFO] [talledLocalContainer]   at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
[INFO] [talledLocalContainer]   at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:123)
[INFO] [talledLocalContainer]   at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:776)
[INFO] [talledLocalContainer]   at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:426)
[INFO] [talledLocalContainer]   at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1656)
[INFO] [talledLocalContainer]   at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:309)
[INFO] [talledLocalContainer]   at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:114)
[INFO] [talledLocalContainer]   at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:402)
[INFO] [talledLocalContainer]   at org.apache.catalina.util.LifecycleBase.setState(LifecycleBase.java:345)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:893)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:846)
[INFO] [talledLocalContainer]   at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:171)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1332)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1322)
[INFO] [talledLocalContainer]   at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317)
[INFO] [talledLocalContainer]   at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
[INFO] [talledLocalContainer]   at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:145)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:866)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:241)
[INFO] [talledLocalContainer]   at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:171)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.StandardService.startInternal(StandardService.java:433)
[INFO] [talledLocalContainer]   at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:171)
[INFO] [talledLocalContainer]   at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:918)
[INFO] [talledLocalContainer]   at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:171)
[INFO] [talledLocalContainer]   at org.apache.catalina.startup.Catalina.start(Catalina.java:795)
[INFO] [talledLocalContainer]   at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
[INFO] [talledLocalContainer]   at java.base/java.lang.reflect.Method.invoke(Method.java:580)
[INFO] [talledLocalContainer]   at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:347)
[INFO] [talledLocalContainer]   at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:478)
[INFO] [talledLocalContainer] Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [jakarta.servlet.Filter]: Factory method 'springSecurityFilterChain
' threw exception with message: Section 4.4 of the Servlet 3.0 specification does not permit this method to be called from a ServletContextListener that was not defined in web.xml, a w
eb-fragment.xml file nor annotated with @WebListener
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:171)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:650)
[INFO] [talledLocalContainer]   ... 56 more
[INFO] [talledLocalContainer] Caused by: java.lang.UnsupportedOperationException: Section 4.4 of the Servlet 3.0 specification does not permit this method to be called from a ServletCo
ntextListener that was not defined in web.xml, a web-fragment.xml file nor annotated with @WebListener
[INFO] [talledLocalContainer]   at org.apache.catalina.core.StandardContext$NoPluggabilityServletContext.getServletRegistrations(StandardContext.java:6197)
[INFO] [talledLocalContainer]   at org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry.mappableServletRegistrations(AbstractRequestMatcherRegistry.java:21
5)
[INFO] [talledLocalContainer]   at org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry.requestMatchers(AbstractRequestMatcherRegistry.java:199)
[INFO] [talledLocalContainer]   at org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry.requestMatchers(AbstractRequestMatcherRegistry.java:276)
[INFO] [talledLocalContainer]   at com.example.demo.SecurityConfig.lambda$ignoringCustomizer$0(SecurityConfig.java:39)
[INFO] [talledLocalContainer]   at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:119
)
[INFO] [talledLocalContainer]   at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
[INFO] [talledLocalContainer]   at java.base/java.lang.reflect.Method.invoke(Method.java:580)
[INFO] [talledLocalContainer]   at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:139)
[INFO] [talledLocalContainer]   ... 57 more
[INFO] [talledLocalContainer] 
[INFO] [talledLocalContainer] 9月 12, 2023 5:10:20 下午 org.apache.catalina.core.StandardContext startInternal
[INFO] [talledLocalContainer] SEVERE: One or more listeners failed to start. Full details will be found in the appropriate container log file
[INFO] [talledLocalContainer] 9月 12, 2023 5:10:20 下午 org.apache.catalina.core.StandardContext startInternal
[INFO] [talledLocalContainer] SEVERE: Context [/demo] startup failed due to previous errors

There is a line indicate it is caused by WebSecurityCustomizer

at com.example.demo.SecurityConfig.lambda$ignoringCustomizer$0(SecurityConfig.java:39)

The ignoringCustomizer method is like this.

@Bean
public WebSecurityCustomizer ignoringCustomizer() {
    // antMatchers -> requestMatchers
    return (web) -> web.ignoring().requestMatchers("/css/**", "/images/**");
}

Reproducible Example

Check this minimal, reproducible sample.

@hantsy hantsy added status: waiting-for-triage An issue we've not yet triaged type: bug A general bug labels Sep 12, 2023
@marcusdacoregio
Copy link
Contributor

Hi, @hantsy. This seems related to #13789.
I'll close this as duplicate and we can keep the discussion on the other issue.

@marcusdacoregio marcusdacoregio self-assigned this Sep 12, 2023
@marcusdacoregio marcusdacoregio added status: duplicate A duplicate of another issue and removed status: waiting-for-triage An issue we've not yet triaged labels Sep 12, 2023
@hantsy
Copy link
Author

hantsy commented Sep 13, 2023

But it seems it was introduced in Spring Security 6.2 branch, in the previous Spring 6.0.x/Spring Security 6.1.x stable baseline, it worked.

@hantsy
Copy link
Author

hantsy commented Sep 27, 2023

Still encountered this issue when updating to Spring Security 6.2.0-M3.

@mainul35
Copy link

mainul35 commented Nov 1, 2023

I also faced the same problem and this is a bug of Spring Security.

@hantsy
Copy link
Author

hantsy commented Nov 8, 2023

@marcusdacoregio It seems it is not same as #13789.

I have updated to use the latest Tomcat 10.1/Jetty 12, and now add WildFly 30.0.0.Final, all are Servlet 6.0 containers.

When running mvn clean wildfly:run -Pwildfly, and got the exceptions like the following.

12:16:51,959 WARN  [org.springframework.web.context.support.AnnotationConfigWebApplicationContext] (ServerService Thread Pool -- 29) Exception encountered during context initialization
 - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.confi
guration.WebSecurityConfiguration': Unsatisfied dependency expressed through method 'setFilterChains' parameter 0: Error creating bean with name 'apiFilterChain' defined in com.example
.demo.SecurityConfig: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw exception with message: UT010042: This method 
cannot be called from a servlet context listener that has been added programatically
12:16:51,963 ERROR [org.springframework.web.context.ContextLoader] (ServerService Thread Pool -- 29) Context initialization failed: org.springframework.beans.factory.UnsatisfiedDepende
ncyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Unsatisfied dependency expressed through method
 'setFilterChains' parameter 0: Error creating bean with name 'apiFilterChain' defined in com.example.demo.SecurityConfig: Failed to instantiate [org.springframework.security.web.Secur
ityFilterChain]: Factory method 'apiFilterChain' threw exception with message: UT010042: This method cannot be called from a servlet context listener that has been added programaticall
y
        at deployment.demo.war//org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.resolveMethodArguments(AutowiredAnnotationBeanP
ostProcessor.java:880)
        at deployment.demo.war//org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.jav
a:833)
        at deployment.demo.war//org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:145)
        at deployment.demo.war//org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:493)  
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1420)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:600)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:523)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325)
        at deployment.demo.war//org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
        at deployment.demo.war//org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:973)
        at deployment.demo.war//org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:946)
        at deployment.demo.war//org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:616)
        at deployment.demo.war//org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:394)
        at deployment.demo.war//org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:274)
        at deployment.demo.war//org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:102)
        at io.undertow.servlet@2.3.10.Final//io.undertow.servlet.core.ApplicationListeners.contextInitialized(ApplicationListeners.java:187)
        at io.undertow.servlet@2.3.10.Final//io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:219)
        at io.undertow.servlet@2.3.10.Final//io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:187)
        at io.undertow.servlet@2.3.10.Final//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42)
        at io.undertow.servlet@2.3.10.Final//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
        at org.wildfly.extension.undertow@30.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploy
mentInfoService.java:1413)
        at org.wildfly.extension.undertow@30.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploy
mentInfoService.java:1413)
        at org.wildfly.extension.undertow@30.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploy
mentInfoService.java:1413)
        at org.wildfly.extension.undertow@30.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploy
mentInfoService.java:1413)
        at io.undertow.servlet@2.3.10.Final//io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:255)
        at org.wildfly.extension.undertow@30.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:88)
        at org.wildfly.extension.undertow@30.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:70)
        at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:572)
        at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1990)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
        at java.base/java.lang.Thread.run(Thread.java:1583)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.JBossThread.run(JBossThread.java:513)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'apiFilterChain' defined in com.example.demo.SecurityConfig: Failed to instantiate [or
g.springframework.security.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw exception with message: UT010042: This method cannot be called from a servlet context listene
r that has been added programatically
        at deployment.demo.war//org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:655)
        at deployment.demo.war//org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:643)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1336)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1166)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:563)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:523)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325)
        at deployment.demo.war//org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
        at deployment.demo.war//org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:254)
        at deployment.demo.war//org.springframework.beans.factory.support.DefaultListableBeanFactory.addCandidateEntry(DefaultListableBeanFactory.java:1687)
        at deployment.demo.war//org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1651)
        at deployment.demo.war//org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeanCollection(DefaultListableBeanFactory.java:1541)
        at deployment.demo.war//org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeans(DefaultListableBeanFactory.java:1509)
        at deployment.demo.war//org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1390)
        at deployment.demo.war//org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1348)
        at deployment.demo.war//org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.resolveMethodArguments(AutowiredAnnotationBeanP
ostProcessor.java:872)
        ... 36 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw exc
eption with message: UT010042: This method cannot be called from a servlet context listener that has been added programatically
        at deployment.demo.war//org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:178)
        at deployment.demo.war//org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
        ... 53 more
Caused by: java.lang.UnsupportedOperationException: UT010042: This method cannot be called from a servlet context listener that has been added programatically
        at io.undertow.servlet@2.3.10.Final//io.undertow.servlet.spec.ServletContextImpl.ensureNotProgramaticListener(ServletContextImpl.java:1018)
        at io.undertow.servlet@2.3.10.Final//io.undertow.servlet.spec.ServletContextImpl.getServletRegistrations(ServletContextImpl.java:592)
        at deployment.demo.war//org.springframework.security.config.annotation.web.configurers.ServletRegistrationCollection.registrations(ServletRegistrationCollection.java:54)       
        at deployment.demo.war//org.springframework.security.config.annotation.web.configurers.RequestMatcherBuilders.createDefault(RequestMatcherBuilders.java:89)
        at deployment.demo.war//org.springframework.security.config.annotation.web.configurers.AbstractRequestMatcherBuilderRegistry.<init>(AbstractRequestMatcherBuilderRegistry.java:2
9)
        at deployment.demo.war//org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer$AuthorizationManagerRequestMatcherRegistry.<init>(Authori
zeHttpRequestsConfigurer.java:163)
        at deployment.demo.war//org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer.<init>(AuthorizeHttpRequestsConfigurer.java:82)
        at deployment.demo.war//org.springframework.security.config.annotation.web.builders.HttpSecurity.authorizeHttpRequests(HttpSecurity.java:1466)
        at deployment.demo.war//com.example.demo.SecurityConfig.apiFilterChain(SecurityConfig.java:48)
        at deployment.demo.war//com.example.demo.SecurityConfig$$SpringCGLIB$$0.CGLIB$apiFilterChain$2(<generated>)
        at deployment.demo.war//com.example.demo.SecurityConfig$$SpringCGLIB$$FastClass$$1.invoke(<generated>)
        at deployment.demo.war//org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:258)
        at deployment.demo.war//org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331)
        at deployment.demo.war//com.example.demo.SecurityConfig$$SpringCGLIB$$0.apiFilterChain(<generated>)
        at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
        at java.base/java.lang.reflect.Method.invoke(Method.java:580)
        at deployment.demo.war//org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:140)
        ... 54 more

12:16:52,283 INFO  [io.undertow.servlet] (ServerService Thread Pool -- 29) Closing Spring root WebApplicationContext
12:16:52,288 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 29) MSC000001: Failed to start service jboss.deployment.unit."demo.war".undertow-deployment: org.jboss.msc
.service.StartException in service jboss.deployment.unit."demo.war".undertow-deployment: java.lang.RuntimeException: org.springframework.beans.factory.UnsatisfiedDependencyException: E
rror creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Unsatisfied dependency expressed through method 'setFilterChai
ns' parameter 0: Error creating bean with name 'apiFilterChain' defined in com.example.demo.SecurityConfig: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]
: Factory method 'apiFilterChain' threw exception with message: UT010042: This method cannot be called from a servlet context listener that has been added programatically
        at org.wildfly.extension.undertow@30.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:73)
        at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:572)
        at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1990)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
        at java.base/java.lang.Thread.run(Thread.java:1583)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.JBossThread.run(JBossThread.java:513)
Caused by: java.lang.RuntimeException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.w
eb.configuration.WebSecurityConfiguration': Unsatisfied dependency expressed through method 'setFilterChains' parameter 0: Error creating bean with name 'apiFilterChain' defined in com
.example.demo.SecurityConfig: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw exception with message: UT010042: This
 method cannot be called from a servlet context listener that has been added programatically
        at io.undertow.servlet@2.3.10.Final//io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:257)
        at org.wildfly.extension.undertow@30.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:88)
        at org.wildfly.extension.undertow@30.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:70)
        ... 8 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurity
Configuration': Unsatisfied dependency expressed through method 'setFilterChains' parameter 0: Error creating bean with name 'apiFilterChain' defined in com.example.demo.SecurityConfig
: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw exception with message: UT010042: This method cannot be called fro
m a servlet context listener that has been added programatically
        at deployment.demo.war//org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.resolveMethodArguments(AutowiredAnnotationBeanP
ostProcessor.java:880)
        at deployment.demo.war//org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.jav
a:833)
        at deployment.demo.war//org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:145)
        at deployment.demo.war//org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:493)  
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1420)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:600)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:523)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325)
        at deployment.demo.war//org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
        at deployment.demo.war//org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:973)
        at deployment.demo.war//org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:946)
        at deployment.demo.war//org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:616)
        at deployment.demo.war//org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:394)
        at deployment.demo.war//org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:274)
        at deployment.demo.war//org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:102)
        at io.undertow.servlet@2.3.10.Final//io.undertow.servlet.core.ApplicationListeners.contextInitialized(ApplicationListeners.java:187)
        at io.undertow.servlet@2.3.10.Final//io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:219)
        at io.undertow.servlet@2.3.10.Final//io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:187)
        at io.undertow.servlet@2.3.10.Final//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42)
        at io.undertow.servlet@2.3.10.Final//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
        at org.wildfly.extension.undertow@30.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploy
mentInfoService.java:1413)
        at org.wildfly.extension.undertow@30.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploy
mentInfoService.java:1413)
        at org.wildfly.extension.undertow@30.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploy
mentInfoService.java:1413)
        at org.wildfly.extension.undertow@30.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploy
mentInfoService.java:1413)
        at io.undertow.servlet@2.3.10.Final//io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:255)
        ... 10 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'apiFilterChain' defined in com.example.demo.SecurityConfig: Failed to instantiate [or
g.springframework.security.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw exception with message: UT010042: This method cannot be called from a servlet context listene
r that has been added programatically
        at deployment.demo.war//org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:655)
        at deployment.demo.war//org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:643)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1336)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1166)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:563)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:523)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325)
        at deployment.demo.war//org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323)
        at deployment.demo.war//org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
        at deployment.demo.war//org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:254)
        at deployment.demo.war//org.springframework.beans.factory.support.DefaultListableBeanFactory.addCandidateEntry(DefaultListableBeanFactory.java:1687)
        at deployment.demo.war//org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1651)
        at deployment.demo.war//org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeanCollection(DefaultListableBeanFactory.java:1541)
        at deployment.demo.war//org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeans(DefaultListableBeanFactory.java:1509)
        at deployment.demo.war//org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1390)
        at deployment.demo.war//org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1348)
        at deployment.demo.war//org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.resolveMethodArguments(AutowiredAnnotationBeanP
ostProcessor.java:872)
        ... 36 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw exc
eption with message: UT010042: This method cannot be called from a servlet context listener that has been added programatically
        at deployment.demo.war//org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:178)
        at deployment.demo.war//org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
        ... 53 more
Caused by: java.lang.UnsupportedOperationException: UT010042: This method cannot be called from a servlet context listener that has been added programatically
        at io.undertow.servlet@2.3.10.Final//io.undertow.servlet.spec.ServletContextImpl.ensureNotProgramaticListener(ServletContextImpl.java:1018)
        at io.undertow.servlet@2.3.10.Final//io.undertow.servlet.spec.ServletContextImpl.getServletRegistrations(ServletContextImpl.java:592)
        at deployment.demo.war//org.springframework.security.config.annotation.web.configurers.ServletRegistrationCollection.registrations(ServletRegistrationCollection.java:54)       
        at deployment.demo.war//org.springframework.security.config.annotation.web.configurers.RequestMatcherBuilders.createDefault(RequestMatcherBuilders.java:89)
        at deployment.demo.war//org.springframework.security.config.annotation.web.configurers.AbstractRequestMatcherBuilderRegistry.<init>(AbstractRequestMatcherBuilderRegistry.java:2
9)
        at deployment.demo.war//org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer$AuthorizationManagerRequestMatcherRegistry.<init>(Authori
zeHttpRequestsConfigurer.java:163)
        at deployment.demo.war//org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer.<init>(AuthorizeHttpRequestsConfigurer.java:82)
        at deployment.demo.war//org.springframework.security.config.annotation.web.builders.HttpSecurity.authorizeHttpRequests(HttpSecurity.java:1466)
        at deployment.demo.war//com.example.demo.SecurityConfig.apiFilterChain(SecurityConfig.java:48)
        at deployment.demo.war//com.example.demo.SecurityConfig$$SpringCGLIB$$0.CGLIB$apiFilterChain$2(<generated>)
        at deployment.demo.war//com.example.demo.SecurityConfig$$SpringCGLIB$$FastClass$$1.invoke(<generated>)
        at deployment.demo.war//org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:258)
        at deployment.demo.war//org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331)
        at deployment.demo.war//com.example.demo.SecurityConfig$$SpringCGLIB$$0.apiFilterChain(<generated>)
        at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
        at java.base/java.lang.reflect.Method.invoke(Method.java:580)
        at deployment.demo.war//org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:140)
        ... 54 more

12:16:52,692 ERROR [org.jboss.as.controller.management-operation] (management-handler-thread - 1) WFLYCTL0013: Operation ("add") failed - address: ([("deployment" => "demo.war")]) - fa
ilure description: {"WFLYCTL0080: Failed services" => {"jboss.undertow.deployment.default-server.default-host./demo" => "java.lang.RuntimeException: org.springframework.beans.factory.U
nsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Unsatisfied dependency express
ed through method 'setFilterChains' parameter 0: Error creating bean with name 'apiFilterChain' defined in com.example.demo.SecurityConfig: Failed to instantiate [org.springframework.s
ecurity.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw exception with message: UT010042: This method cannot be called from a servlet context listener that has been add
ed programatically
    Caused by: java.lang.RuntimeException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotati
on.web.configuration.WebSecurityConfiguration': Unsatisfied dependency expressed through method 'setFilterChains' parameter 0: Error creating bean with name 'apiFilterChain' defined in
 com.example.demo.SecurityConfig: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw exception with message: UT010042: 
This method cannot be called from a servlet context listener that has been added programatically
    Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecu
rityConfiguration': Unsatisfied dependency expressed through method 'setFilterChains' parameter 0: Error creating bean with name 'apiFilterChain' defined in com.example.demo.SecurityCo
nfig: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw exception with message: UT010042: This method cannot be called
 from a servlet context listener that has been added programatically
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'apiFilterChain' defined in com.example.demo.SecurityConfig: Failed to instantiate
 [org.springframework.security.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw exception with message: UT010042: This method cannot be called from a servlet context lis
tener that has been added programatically
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw
 exception with message: UT010042: This method cannot be called from a servlet context listener that has been added programatically
    Caused by: java.lang.UnsupportedOperationException: UT010042: This method cannot be called from a servlet context listener that has been added programatically"}}
12:16:52,703 ERROR [org.jboss.as.controller.management-operation] (management-handler-thread - 1) WFLYCTL0013: Operation ("add") failed - address: ([("deployment" => "demo.war")]) - fa
ilure description: {"WFLYCTL0080: Failed services" => {"jboss.undertow.deployment.default-server.default-host./demo" => "java.lang.RuntimeException: org.springframework.beans.factory.U
nsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Unsatisfied dependency express
ed through method 'setFilterChains' parameter 0: Error creating bean with name 'apiFilterChain' defined in com.example.demo.SecurityConfig: Failed to instantiate [org.springframework.s
ecurity.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw exception with message: UT010042: This method cannot be called from a servlet context listener that has been add
ed programatically
    Caused by: java.lang.RuntimeException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotati
on.web.configuration.WebSecurityConfiguration': Unsatisfied dependency expressed through method 'setFilterChains' parameter 0: Error creating bean with name 'apiFilterChain' defined in
 com.example.demo.SecurityConfig: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw exception with message: UT010042: 
This method cannot be called from a servlet context listener that has been added programatically
    Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecu
rityConfiguration': Unsatisfied dependency expressed through method 'setFilterChains' parameter 0: Error creating bean with name 'apiFilterChain' defined in com.example.demo.SecurityCo
nfig: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw exception with message: UT010042: This method cannot be called
 from a servlet context listener that has been added programatically
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'apiFilterChain' defined in com.example.demo.SecurityConfig: Failed to instantiate
 [org.springframework.security.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw exception with message: UT010042: This method cannot be called from a servlet context lis
tener that has been added programatically
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw
 exception with message: UT010042: This method cannot be called from a servlet context listener that has been added programatically
    Caused by: java.lang.UnsupportedOperationException: UT010042: This method cannot be called from a servlet context listener that has been added programatically"}}
12:16:52,718 INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-1) WFLYJCA0019: Stopped Driver service with driver-name = demo.war_org.postgresql.Driver_42_6
12:16:52,767 ERROR [org.jboss.as.server] (management-handler-thread - 1) WFLYSRV0021: Deploy of deployment "demo.war" was rolled back with the following failure message:
{"WFLYCTL0080: Failed services" => {"jboss.undertow.deployment.default-server.default-host./demo" => "java.lang.RuntimeException: org.springframework.beans.factory.UnsatisfiedDependenc
yException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Unsatisfied dependency expressed through method '
setFilterChains' parameter 0: Error creating bean with name 'apiFilterChain' defined in com.example.demo.SecurityConfig: Failed to instantiate [org.springframework.security.web.Securit
yFilterChain]: Factory method 'apiFilterChain' threw exception with message: UT010042: This method cannot be called from a servlet context listener that has been added programatically 
    Caused by: java.lang.RuntimeException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotati
on.web.configuration.WebSecurityConfiguration': Unsatisfied dependency expressed through method 'setFilterChains' parameter 0: Error creating bean with name 'apiFilterChain' defined in
 com.example.demo.SecurityConfig: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw exception with message: UT010042: 
This method cannot be called from a servlet context listener that has been added programatically
    Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecu
rityConfiguration': Unsatisfied dependency expressed through method 'setFilterChains' parameter 0: Error creating bean with name 'apiFilterChain' defined in com.example.demo.SecurityCo
nfig: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw exception with message: UT010042: This method cannot be called
 from a servlet context listener that has been added programatically
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'apiFilterChain' defined in com.example.demo.SecurityConfig: Failed to instantiate
 [org.springframework.security.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw exception with message: UT010042: This method cannot be called from a servlet context lis
tener that has been added programatically
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'apiFilterChain' threw
 exception with message: UT010042: This method cannot be called from a servlet context listener that has been added programatically
    Caused by: java.lang.UnsupportedOperationException: UT010042: This method cannot be called from a servlet context listener that has been added programatically"}}
12:16:53,699 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-1) WFLYSRV0028: Stopped deployment demo.war (runtime-name: demo.war) in 987ms

@hantsy
Copy link
Author

hantsy commented Nov 8, 2023

@marcusdacoregio The issue #13789 fixes nothing and closed.

Note, but in my example project, I am using the latest Servlet 6.0 containers for test purpose, not a legacy Servlet container.

And I also mentioned, the previous example project using Spring 6.0/Spring Security 6.1 working well with Tomcat 10 and Jetty 11(Jakarta EE 9).

This is an issue I found in the upgrade progress to latest Spring 6.1/Spring Security 6.2 stack and the latest Jakarta EE 10 spec.

This issue should be a blocking issue of releasing Spring Security 6.2.0 GA.

@marcusdacoregio
Copy link
Contributor

marcusdacoregio commented Nov 8, 2023

Hi, @hantsy. Can you please provide a minimal, reproducible sample? I can reproduce it with your sample but there is a lot going on there. Can you please use only the minimal dependencies and configuration that triggers the error?

@marcusdacoregio marcusdacoregio removed the status: duplicate A duplicate of another issue label Nov 8, 2023
@mklinkj
Copy link

mklinkj commented Nov 16, 2023

hello.

I've created a simple example related to this issue.

Example Project URL

Example Project Zip File

Example project environment

  • Spring 5.3.30
  • Spring Security
    • 5.8.4: No problem.
    • 5.8.8: Exception thrown when running WAS. (Version 5.8.5 and later)
  • Running WAS with Gretty
    • Tomcat 9.0.82
    • Jetty 10.0.18

First, Spring Security version 5.8.4 is fine.

Starting with 5.8.5 and later versions, the exception below occurs.

In 5.8.5 and later, to run without exceptions, you had to use antMatcher() like the code below.

    http.authorizeHttpRequests(
            (authz) ->
                authz
                    /*
                    .requestMatchers(
                        "/webjars/**", //
                        "/resources/**",
                        "/",
                        "/index",
                        "/login",
                        "/favicon.ico")
                    */
                    .requestMatchers(
                        antMatcher("/webjars/**"), //
                        antMatcher("/resources/**"),
                        antMatcher("/"),
                        antMatcher("/index"),
                        antMatcher("/login"),
                        antMatcher("/favicon.ico"))
                    .permitAll()
                    // .requestMatchers("/admin")
                    .requestMatchers(antMatcher("/admin"))
                    .hasAuthority("ADMIN")
                    .anyRequest()
                    .authenticated())

How to run the example project

  • Tomcat 9.0.82

    • Set Gretty's settings in build.gradle to servletContainer = "tomcat9"

      ./gradlew clean appRun
      
  • Jetty 10.0.18

    • Set Gretty's settings in build.gradle to servletContainer = "jetty10"

      ./gradlew clean appRun

Exceptions that occur when running with Tomcat 9.0.82

Caused by: java.lang.UnsupportedOperationException: Section 4.4 of the Servlet 3.0 specification does not permit this method to be called from a ServletContextListener that was not defined in web.xml, a web-fragment.xml file nor annotated with @WebListener
        at org.apache.catalina.core.StandardContext$NoPluggabilityServletContext.getServletRegistrations(StandardContext.java:6306)
        at org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry.mappableServletRegistrations(AbstractRequestMatcherRegistry.java:333)
        at org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry.requestMatchers(AbstractRequestMatcherRegistry.java:317)
        at org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry.requestMatchers(AbstractRequestMatcherRegistry.java:394)
        at org.mklinkj.qna.spring_security.security.HelloSecurityConfig.lambda$securityFilterChain$0(HelloSecurityConfig.java:50)
        ...

Exceptions encountered when running with Jetty 10.0.18

Caused by:
java.lang.UnsupportedOperationException
        at org.eclipse.jetty.servlet.ServletContextHandler$Context.getServletRegistrations(ServletContextHandler.java:1385)
        at org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry.mappableServletRegistrations(AbstractRequestMatcherRegistry.java:333)
        at org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry.requestMatchers(AbstractRequestMatcherRegistry.java:317)
        at org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry.requestMatchers(AbstractRequestMatcherRegistry.java:394)
        at org.mklinkj.qna.spring_security.security.HelloSecurityConfig.lambda$securityFilterChain$0(HelloSecurityConfig.java:50)

I would appreciate your confirmation.

Thank you. Have a nice day. 👍

@hantsy
Copy link
Author

hantsy commented Nov 16, 2023

@mklinkj I am using the latest stack, not an old Servlet container.

And the example project was working well in the Spring 6.0/Spring Security 6.1 before.

@marcusdacoregio The example project: https://github.com/hantsy/spring6-sandbox/tree/master/mvc-freemarker, which uses the latest Spring 6.1 RC and Security 6.2 RC, also set Jakarta EE 10 as base Jakarta EE version. And it includes Maven profiles to run on Tomcat 10.1, Jetty 12 and WildFly 30.0.0.Final.

@hantsy hantsy changed the title WebSecurityCustomizer faild tomcat or Jetty startup Security configuration is initialzied failed in a Servlet 6.0 container Nov 16, 2023
@hantsy hantsy changed the title Security configuration is initialzied failed in a Servlet 6.0 container Security configuration is failed to be initialized in a Servlet 6.0 container Nov 16, 2023
@mklinkj
Copy link

mklinkj commented Nov 17, 2023

hello.

I tried changing the example project to a Servlet 6 (Tomcat 10.1.16) + Spring 6.0.13 + Spring Security 6.1.x environment.

It works fine with Spring Security 6.1.1.
But on 6.1.2 through 6.1.5, I get the same exception.

@hantsy
Copy link
Author

hantsy commented Nov 17, 2023

Yes, my example project is working well with the stable version. But I am trying to update the latest development(upcoming version) in my example project, it is failed.

@hantsy
Copy link
Author

hantsy commented Nov 17, 2023

Update Spring to 6.1.0 in my example project, failed.

@jzheaux jzheaux added this to the 5.8.9 milestone Nov 17, 2023
@jzheaux jzheaux added the in: config An issue in spring-security-config label Nov 17, 2023
@jzheaux jzheaux self-assigned this Nov 17, 2023
@jzheaux
Copy link
Contributor

jzheaux commented Nov 17, 2023

Thanks for the report and the sample. I've deferred the ServletContext-based validations to runtime by first testing to see if they are available.

This won't affect Boot applications as the ServletContext API is available at runtime in those circumstances.

Will you please check the SNAPSHOT version to see if the issue is resolved?

@mklinkj
Copy link

mklinkj commented Nov 17, 2023

hello.

I applied 5.8.9-SANPSHOT to the example project,
no exception is thrown on server startup, but when accessing the page, the same exception is thrown.

@hantsy
Copy link
Author

hantsy commented Nov 18, 2023

I have updated my example project to use the snapshot version, and got the following result.

Firstly startup a db by docker compose file in the repo root.

docker compose up postgres

Then start to build and deploy on Servlet containers.

mvn clean package cargo:run -Ptomcat 
mvn clean package cargo:run -Pjetty
mvn clean wildfly:run -Pwildfly

All are started successfully.

Tomcat 10.1.15

Tomcat startup is ok, when accessing the home page, http://localhost:8080/demo/posts and got exception as following, I can not go through any pages.

[INFO] [talledLocalContainer] java.lang.UnsupportedOperationException: 
Section 4.4 of the Servlet 3.0 specification does not permit this method to be 
called from a ServletContextListener that was not defined in web.xml, a 
web-fragment.xml file nor annotated with @WebListener

From https://tomcat.apache.org/whichversion.html, Tomcat 10.1.x should also include Servlet 6.0 spec support.

Jetty 12.0.3

Jetty is running well, open browser and navigate http://localhost:8080/demo/posts, redirect to login page, login is ok.

But some endpoint protection does not work as expected.

  • Logged in as user/password.
  • In the new posts page, add title and content.
  • Save post will cause a 403 error.

The same error will be occurred on updating posts.

From the logging, it seems it is failed due to a Csrf token. I do not use any csrf hidden form fields in my freemarker template. Not sure why it triggers the csrf token validation.

  • I have to disable it explicitly if do not want to use it?
  • If I only want to use csrf in some forms(not all forms), how to process it?

Wildfly 30.0.0.Final

Similar to Jetty, start up is ok, when accessing http://localhost:8080/demo/posts, go to login page, login is ok. but got Forbidden when adding new posts.

@mklinkj
Copy link

mklinkj commented Nov 18, 2023

@hantsy
I think it's great that the cargo maven plugin supports various WAS.
have a nice day 👍

@hantsy
Copy link
Author

hantsy commented Nov 18, 2023

@mklinkj Cargo maven plugin almost supports all popular application server, https://codehaus-cargo.github.io/cargo/Maven+3+Plugin.html, including WebSphere

@hantsy
Copy link
Author

hantsy commented Nov 22, 2023

Spring Security 6.2 GA and Tomcat 10.1.16, got the same result as #13794 (comment)

When disabled CSRF, working well on Jetty and WildFly.

jzheaux added a commit to jzheaux/spring6-sandbox that referenced this issue Nov 29, 2023
By Placing it as part of the Servlet Config, it isn't loaded
via a programmatic listener by Spring, thus allowing it to use
the ServletRegistration API. While the 6.2 release addresses this
by deferring those checks til runtime, having them available at
startup will provide a performance benefit as well as the benefit
of knowing at startup time if there is an insecure configuration
to be corrected.

Related to spring-projects/spring-security#13794
@jzheaux
Copy link
Contributor

jzheaux commented Nov 30, 2023

Thanks, @hantsy. Unfortunately, I'm not able to reproduce your last observation. When I use your latest update to mvc-freemarker and re-enable CSRF, the reason that those posts fail is that there is no CSRF token present in the request. If I further edit edit.ftl to include the CSRF token as a hidden input value, then the edit succeeds.

That said, I'm concerned that the application is simply too big for you and me to make further progress quickly. If you continue to have issues, please simplify the project to the simplest form possible that still reproduces the issue you are seeing. If it is a different issue from the Servlet Spec issue reported, please file a separate issue at this point.

Additionally, I've sent a PR to your repo with a suggested optimization that adjusts the loading order for Spring Security. There is a further explanation in the PR itself.

hantsy pushed a commit to hantsy/spring6-sandbox that referenced this issue Nov 30, 2023
By Placing it as part of the Servlet Config, it isn't loaded
via a programmatic listener by Spring, thus allowing it to use
the ServletRegistration API. While the 6.2 release addresses this
by deferring those checks til runtime, having them available at
startup will provide a performance benefit as well as the benefit
of knowing at startup time if there is an insecure configuration
to be corrected.

Related to spring-projects/spring-security#13794
@hantsy
Copy link
Author

hantsy commented Nov 30, 2023

@jzheaux Firstly thanks for PR to resolve my issues.

But I check the latest Spring docs, https://docs.spring.io/spring-security/reference/servlet/configuration/java.html#abstractsecuritywebapplicationinitializer-with-spring-mvc.

In the Java configuration with a Spring MVC section, it still suggest register a spring security config in the getRootConfigClasses.

This only registers the springSecurityFilterChain for every URL in your application. After that, we need to ensure that WebSecurityConfig was loaded in our existing ApplicationInitializer. For example, if we use Spring MVC it is added in the getRootConfigClasses():

public class MvcWebApplicationInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {

@OverRide
protected Class<?>[] getRootConfigClasses() {
return new Class[] { WebSecurityConfig.class };
}

// ... other overrides ...
}

@jzheaux
Copy link
Contributor

jzheaux commented Nov 30, 2023

Thanks, @hantsy, I've added #14220 to address that.

@jzheaux
Copy link
Contributor

jzheaux commented Nov 30, 2023

@mklinkj, please try and apply the same change to your HelloWebInitializer. When using Spring MVC, you should register your security configuration alongside it like so:

public class HelloWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
  @Override
  protected Class<?>[] getRootConfigClasses() {
    return null;
  }

  @Override
  protected Class<?>[] getServletConfigClasses() {
    return new Class<?>[] {HelloSecurityConfig.class, HelloWebConfig.class};
  }

  @Override
  protected String[] getServletMappings() {
    return new String[] {"/"};
  }
}

And not specify it in HelloSecurityInitializer:

public class HelloSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}

This is largely because Spring Security needs to be able to see some Spring MVC configuration to correctly construct MVC request matchers. It cannot, though, when it is configured in a separate application context (the result of your app's existing arrangement).

You can see an example of this in Spring Security Samples. You can also read some detail about this in the reference, though there is a ticket I've just added to clarify this use case.

Also, I think that the error message could be improved in this case, so I've created #14221 as well to address that.

@mklinkj
Copy link

mklinkj commented Nov 30, 2023

@jzheaux

Thank you for your response.

As you suggested, I moved the Security settings from the constructor of HelloSecurityInitializer to getServletConfigClasses().

I also removed the HandlerMappingIntrospector bean that I was creating on purpose.

I added a test to try to access the example main page once with Gretty (Tomcat 10.1.x), and confirmed that it works fine and doesn't send a 500 response like it used to. (Spring Security 5.8.9-SNAPSHOT environment)

Thank you. Have a good day. 👍


I apologize for the previous test code being incorrect.

There was a potential for occasional test failures because Gretty’s random port was being acquired in the wrong way.

I have made corrections regarding this issue.

Thank you. Have a good day. 👍

jzheaux added a commit that referenced this issue Dec 1, 2023
Tomcat uses different ServletContext instances from startup- and request-time.
This commit ensures that if the programmatic API isn't available at startup-time,
then use the ServletContext attached to the HttpServletRequest at runtime.

Issue gh-13794
@JohnZ1385
Copy link

@jzheaux just curious how this ordering works within the confines of a web.xml .. initially i had my security config defined as such pre spring-security-5.8.9 ..

<web-app version="4.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">

  <display-name>MyConsole</display-name>
  <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
  <context-param>
    <param-name>contextClass</param-name>
    <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
  </context-param>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      com.xxx.product.console.ApplicationContextConfig,
      com.xxx.product.console.SecurityConfig
    </param-value>
  </context-param>

  <!-- Processes application requests -->
  <servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextClass</param-name>
      <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </init-param>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>com.xxx.product.console.ServletConfig</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
 
  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>

of note here my SecurityConfig class is registered at the same level as the root ApplicationContextConfig.
In 5.8.8 this works fine.
Starting in 5.8.9 I see the following error:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Unsatisfied dependency expressed through method 'setFilterChains' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityFilterChain' defined in com.cybershift.ds.console.SecurityConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'securityFilterChain' threw exception; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'A Bean named mvcHandlerMappingIntrospector of type org.springframework.web.servlet.handler.HandlerMappingIntrospector is required to use MvcRequestMatcher. Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext.'

So i moved the SecurityConfig to the Servlet level .. i.e

  <servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextClass</param-name>
      <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </init-param>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
        com.xxx.product.console.ServletConfig,
        com.xxx.product.console.SecurityConfig
      </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

with this configuration I wind up with the following error:

<Dec 20, 2023, 11:43:11,344 AM Alaska Standard Time> <Could not load user defined filter in web.xml: org.springframework.web.filter.DelegatingFilterProxy.
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:874)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1358)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:309)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:283)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:283)
Truncated.

I assume this is because the springSecurityFilterChain is referenced in the web.xml?

Note I'd rather not use the web.xml to begin with, at one point I was using an implementation of WebApplicationInitializer in place of the web.xml but I found that due to me having an EAR file application with WARs within apparently there was some issue with that in the latest spring security releases. I'm trying to find the reference issue but I haven't come across it yet. The code was as follows:

'''
public class ConsoleWebApplicationInitializer implements WebApplicationInitializer {

protected Logger logger = LoggerFactory.getLogger(getClass());

@OverRide
public void onStartup(ServletContext servletContext) throws ServletException {
logger.debug("onStartup(servletContext={})", servletContext);

AnnotationConfigWebApplicationContext rootCtx = new AnnotationConfigWebApplicationContext();
rootCtx.register(ApplicationContextConfig.class, SecurityConfig.class);

servletContext.addListener(new LoggingServiceContextListener());
servletContext.addListener(new ContextLoaderListener(rootCtx));
rootCtx.setServletContext(servletContext);

AnnotationConfigWebApplicationContext servletCtx = new AnnotationConfigWebApplicationContext();
servletCtx.setParent(rootCtx);
servletCtx.register(ServletConfig.class);

ServletRegistration.Dynamic servlet = servletContext.addServlet("appServlet", new DispatcherServlet(servletCtx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");

FilterRegistration.Dynamic security = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy());
security.addMappingForUrlPatterns(null, true, "/*");

}
}
'''

Any suggestions for a path here?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
in: config An issue in spring-security-config type: bug A general bug
Projects
None yet
Development

No branches or pull requests

6 participants