Describe the bug
When using Spring-Boot 2.6.4 + Spring-Security usage of an ApplicationContextRequestMatcher (such as EndpointRequest.to(HealthEndpoint::class.java) from actuator or PathRequest.toH2Console() for h2) will lead to an error java.lang.IllegalArgumentException: ServletContext must not be null when using authorizeHttpRequests and performing an unauthorized request.
The response will also contain unexpected html.
According to my analysis this is because AuthorizationManagerWebInvocationPrivilegeEvaluator creates a FilterInvocation which does not contain the servlet context. This filter invocation is then checked using RequestMatcherDelegatingAuthorizationManager which then passes it to a ApplicationContextRequestMatcher which accesses the servlet context which is null.
This is related to #10779.
To Reproduce Start the sample project and perform a GET http://localhost:8080 without credentials.
Expected behavior No exception is thrown and the response contains no unexpected html.
Sample demo.zip
Comment From: marcusdacoregio
Thanks for the report @mengelbrecht. I've assigned it to the next patch releases, 5.5.6, 5.6.3, and 5.7.0-M3.
Comment From: mengelbrecht
@marcusdacoregio I just tested this with Spring-Boot 2.6.7 which includes Spring-Security 5.6.3 and this issue is still present (can be checked using the sample from my initial post with an updated Spring-Boot version).
Although AuthorizationManagerWebInvocationPrivilegeEvaluator is now ServletContextAware the setServletContext function is never called and thus the servletContext is still null.
Comment From: marcusdacoregio
Hi @mengelbrecht, thanks for testing it fast and reporting it back.
I've opened https://github.com/spring-projects/spring-security/issues/11165 for that and the fix is already committed. It'd be great if you could use the SNAPSHOT version to test your application.
Comment From: mengelbrecht
Hi @marcusdacoregio thanks for the fix. I can confirm that the servlet context is set correctly when using the snapshot version.
However, the response is different when using Spring-Security 5.6.4-SNAPSHOT vs. 5.6.1.
When I use the sample application from my initial post and use the following property server.error.include-message=always and perform a GET http://localhost:8080/ without credentials version 5.6.1 responds with status 401 and body:
{"timestamp":"2022-04-26T06:42:56.242+00:00","status":401,"error":"Unauthorized","message":"Unauthorized","path":"/"}
whereas version 5.6.4-SNAPSHOT returns only status 401 and no body at all.
But maybe this is another issue?
Comment From: marcusdacoregio
It's hard to tell exactly without knowing what your configuration looks like. There are some issues in the Spring Boot repository that may be a clue, if you don't find anything related, please file a new ticket