spring-security: mockJwt() WebTestClientConfigurer with MockMvcWebTestClient throws a NullPointerException.
Describe the bug
mockJwt() WebTestClientConfigurer does not seem to work with MockMvcWebTestClient that was introduced in Spring 5.3 as documented.
To Reproduce
@Test
void getMessagesWebTestClient() {
final WebTestClient testClient = MockMvcWebTestClient.bindTo(this.mockMvc)
.build();
testClient.mutateWith(mockJwt().authorities(new SimpleGrantedAuthority("SCOPE_message:read")))
.get()
.uri("/messages")
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$[0]").isEqualTo("hello")
.jsonPath("$[1]").isEqualTo("world"); ;
}
throws the exception below
java.lang.NullPointerException: Cannot invoke "org.springframework.web.server.adapter.WebHttpHandlerBuilder.filter(org.springframework.web.server.WebFilter[])" because "httpHandlerBuilder" is null
at org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers$JwtMutator.afterConfigurerAdded(SecurityMockServerConfigurers.java:540)
at org.springframework.test.web.reactive.server.DefaultWebTestClientBuilder.apply(DefaultWebTestClientBuilder.java:247)
at org.springframework.test.web.reactive.server.DefaultWebTestClient.mutateWith(DefaultWebTestClient.java:160)
at com.example.demojwttest.MessageControllerTest.getMessagesWebTestClient(MessageControllerTest.java:51)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
while the equivalent following tests work
// MockMvc
@Test
void getMessages() throws Exception {
this.mockMvc.perform(get("/messages")
.with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_message:read"))))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0]").value("hello"))
.andExpect(jsonPath("$[1]").value("world"));
}
// @WithMockUser
@Test
@WithMockUser(authorities = "SCOPE_message:read")
void getMessagesWebTestClientWithMockUser() {
final WebTestClient testClient = MockMvcWebTestClient.bindTo(this.mockMvc)
.build();
testClient.get()
.uri("/messages")
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$[0]").isEqualTo("hello")
.jsonPath("$[1]").isEqualTo("world"); ;
}
Expected behavior
The first example works
About this issue
- Original URL
- State: open
- Created 6 years ago
- Reactions: 10
- Comments: 20 (9 by maintainers)
We just worked our way through this same rabbit hole at my job and came up with a solution that works in the latest versions.
For us, the key pieces were:
WebTestClientin the way described below - do not rely on theWebTestClientthat is auto-configured with@SpringBootTest(webEnvironment = RANDOM_PORT)or similar.mutateWithon theWebTestClientSet your
WebTestClientup like this in your test class:_this portion of the solution was found in https://github.com/spring-projects/spring-security/issues/9304#issuecomment-841495717_
Then, you can annotate your test classes / methods with
@WithMockUseror any custom annotation created with@MockSecurityContext+ a corresponding implementation ofWithSecurityContextFactory(see https://docs.spring.io/spring-security/reference/servlet/test/method.html#test-method-withsecuritycontext)Full working test class calling a controller that echoes the principal’s name:
I think the thing that is causing everyone the most trouble is that you need to mock the security in a WebMVC-first way, not the WebFlux-first way exposed on
WebTestClient.mutateWith(), which as all the above comments point out is only designed to operate on the reactive security stack.This still doesn’t work for me.
@gursahibsahni Sorry the workaround I posted previously, should have removed the
mutateWithmethod. I’ve updated the example and provided a link to a repository that demonstrates the workaround in its entirety.@soasada @membersound I’ve updated the sample above to demonstrate how to workaround CSRF test support not working too.
@rstoyanchev Thanks for the reply. I’d like to figure out a way that Spring Security users can use
WebTestClientusing the same APIs forWebMvcandWebFluxbackends. It is confusing thatmutateWithdoes not work forMockMvcbased tests. What’s more is there is currently no way to use many of Spring Security’s test features whenWebTestClient+MockMvc.Similar also happens in a test with
@Autowired WebTestClient webTestClientand executing awebTestClient.mutateWith(csrf()).post()...:hi i have same issue with webTestClient and get null pointer exception i think because don’t use jwt for webTestClient and i solved this with add @AutoConfigureWebTestClient as class level annotation for integration test
I’m experiencing the same behaviour than @membersound, do you have any workaround?
Since version 6.1 there seems to be a possibility to use
RequestPostProcessorof MockMvc for aMockMvcHttpConnectorinsideWebTestClientConfigurer- see: https://github.com/spring-projects/spring-framework/issues/31298. So it is possible to solve it the following way (kotlin):This is simple kotlin extension function to
WebTestClientallowing passingRequestPostProcessorinstace (i.e.SecurityMockMvcRequestPostProcessors.jwt) tomutateWithmethod. In Java one would need to implementWebTestClientConfigurer. Is there a simpler way to do it?@rwinch as per my https://github.com/spring-projects/spring-framework/pull/30233#pullrequestreview-1637375454, I think we could do something with the
WebTestClient#mutate(WebTestClientConfigurer)hook. For WebFlux use, I believe Spring Security is using theWebHttpHandlerBuilderargument to modify the server. For WebMvc use, it would use theClientHttpConnectorargument which would be theMockMvcClientHttpConnector. We’ll need to make some changes in Spring Framework to allowMockMvcClientHttpConnectorto be mutated and that should make it possible for Spring Security to address this issue.The suggested workaround does not work with the current spring security versions (6.0.2), as csrf token handling has changed quite a bit. So far I was not able to create a working solution.
I think there is some misunderstanding. As of 5.3
WebTestClientcan be used to exercise not only WebFlux but also WebMvc controllers withMockMvcas the server. In other words it’s allMockMvc, and unrelated to WebFlux, and therefore any WebFlux related hooks do not apply.For the most part what can be done directly with
MockMvccan also be done viaMockMvcWebTestClient. For example, you can configure and apply extension hooks toMockMvcjust the same. However since it it a client, it is not as easy to modify individual requests with some special support via server sideFilter. I can work with you more closely if we want to find a way to improve that.For further reference the sections on
WebTestClientandMockMvchave been updated to reflect this. You can also see all the framework samples tests for MockMvc ported to use withWebTestClient.@rstoyanchev Any ideas on how we can get Spring Security to integrate with the
MockMvcWebTestClientsupport? WithWebTestClientwe typically add aWebFilterwhich can access the attribute onServerWebExchangeand that sets up the context, but it doesn’t appear there is a way to do this when usingMockMvcWebTestClient.We need to be able to access the attribute on the
ServerWebExchangethat is populated by themutateWithmethod and use it to setup theSecurityContext.