If there is only one dispatcher servlet in the servlet context, then it would be nice to have a simpler way to construct MvcRequestMatcher instances.
As it is, an application that is constructing an MvcRequestMatcher must do:
@Bean
SecurityFilterChain appSecurity(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception {
MvcRequestMatcher.Builder mvc = new MvcRequestMatcher.Builder(introspector);
http
.securityMatchers((security) -> security.requestMatchers(mvc.pattern("/controller/**")))
/// ...
If they have configured spring.mvc.servlet.path, then they additionally need to provide that to the matcher as well like so:
@Bean
SecurityFilterChain appSecurity(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception {
MvcRequestMatcher.Builder mvc = new MvcRequestMatcher.Builder(introspector).servletPath("/mvc");
http
.securityMatchers((security) -> security.requestMatchers(mvc.pattern("/controller/**")))
/// ...
These two values, the HandlerMappingIntrospector and the servlet path configuration, Spring Boot already knows. Given that, it would be nice if a Boot application could instead do:
@Bean
SecurityFilterChain appSecurity(HttpSecurity http, MvcRequestMatcher.Builder mvc) throws Exception {
http
.securityMatchers((security) -> security.requestMatchers(mvc.pattern("/controller/**")))
/// ...
I think it best to publish this bean in the event that there is only one DispatcherServlet servlet mapping.
The logic would be something like this (pseudocode follows):
@Conditional(ExactlyOneDispatcherServlet.class)
@Bean
MvcRequestMatcher.Builder mvcRequestMatcherBuilder(HandlerMappingIntrospector introspector, WebMvcProperties properties) {
String servletPath = properties.getServlet().getPath();
MvcRequestMatcher.Builder mvc = new MvcRequestMatcher.Builder(introspector)
return ("/".equals(servletPath)) ? mvc : mvc.servletPath(servletPath);
}
where ExactlyOneDispatcherServlet checks the servlet configuration for multiple servlet mappings tied to servlets of type DispatcherServlet.
In Spring Security 6.2, the need for an MvcRequestMatcher when using authorizeHttpRequests is greatly reduced. That said, it will still be needed for the foreseeable future when activating the default servlet or when using the securityMatchers, csrf#ignoringRequestMatchers, and requiresSecure DSLs.