Describe the bug See https://github.com/spring-projects/spring-boot/issues/27728 for background.

When using the following Thymeleaf markup:

<div sec:authorize-url="/admin"> /admin is accessable</div>

The following exception is thrown if the getServletContext is called on the request.

java.lang.UnsupportedOperationException: public abstract javax.servlet.ServletContext javax.servlet.ServletRequest.getServletContext() is not supported
    at org.springframework.security.web.FilterInvocation$UnsupportedOperationExceptionInvocationHandler.invoke(FilterInvocation.java:304) ~[spring-security-web-5.5.1.jar:5.5.1]
    at com.sun.proxy.$Proxy93.getServletContext(Unknown Source) ~[na:na]
    at javax.servlet.ServletRequestWrapper.getServletContext(ServletRequestWrapper.java:369) ~[tomcat-embed-core-9.0.50.jar:4.0.FR]
    at org.springframework.boot.security.servlet.ApplicationContextRequestMatcher.matches(ApplicationContextRequestMatcher.java:58) ~[spring-boot-2.5.3.jar:2.5.3]

I think this is because this Thymeleaf code uses a WebInvocationPrivilegeEvaluator to determine if path can be used. The WebInvocationPrivilegeEvaluator creates a DummyRequest which throws the error.

To Reproduce Run https://github.com/tvahrst/springboot-security-thymeleaf and hit localhost:8080/main

Expected behavior Thymeleaf has a IWebContext which has access to ServletContext. If WebInvocationPrivilegeEvaluator has a isAllowed method that could accept the context then it could be passed along.

Alternatively, there's a WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE which Thymleaf checks. Spring Security could add this attribute with the ServletContext propagated from the request.

Sample https://github.com/tvahrst/springboot-security-thymeleaf

Comment From: philwebb

Discussing this issue today on our call and @wilkinsona suggested another fix might be to make the WebInvocationPrivilegeEvaluator bean ServletContextAware.

Comment From: marcusdacoregio

Also, @rwinch suggested that we can allow DefaultWebInvocationPrivilegeEvaluator to optionally access the current HttpServletRequest (by enabling it via a property, or so) from RequestContextHolder, and construct FilterInvocation with this request.