liveBook · Manning

MVC matcher

As explained in Spring Security in Action, Second Edition

MvcRequestMatcher is a Spring Security request matcher that evaluates paths using Spring MVC request-mapping conventions.

An MVC matcher selects HTTP requests for Spring Security rules using path patterns aligned with Spring MVC mappings. Use it to apply different authorization restrictions to the same path by HTTP method, or match paths independently of method. section 8.2

Choose a pattern according to the endpoint shape:

  • `/a` matches only `/a`; `/a/*` matches one additional pathname; `/a/**` matches multiple pathnames, including `/a/b/c`. section 8.2
  • Use `requestMatchers(HttpMethod method, String... patterns)` when GET and POST requests on one path need different restrictions. section 8.2
  • Use `requestMatchers(String... patterns)` when the restriction depends only on the path and should cover any HTTP method. section 8.2
  • Match path variables with `/a/{param}` or constrain them with `/a/{param:regex}`. section 8.2

Authorize a path variable by value

For `@GetMapping("/product/{code}")`, configure `requestMatchers("/product/{code:^[0-9]*$}").permitAll().anyRequest().denyAll()`. A request for `/product/12345` is permitted, while `/product/1234a` is denied. section 8.2

HandlerMappingIntrospector i = new HandlerMappingIntrospector();
MvcRequestMatcher r = new MvcRequestMatcher(i, "/ciao");
c.ignoringRequestMatchers(r);

Construct an MvcRequestMatcher with a HandlerMappingIntrospector when a RequestMatcher object is needed, such as excluding a path from CSRF protection. section 9.3

How Spring Security in Action, Second Edition covers it

How deep it goes
Explains overloads, ANT patterns, path variables, regex constraints, and matcher construction, but does not descend into matcher internals.
Examples
Uses `/a`, `/a/b/**`, and `/product/{code:^[0-9]*$}` to demonstrate method rules, recursive paths, and constrained path variables.
What you can do after
Apply it via Spring Security requestMatchers to authorize or exclude selected MVC-style request paths.
How it connects
Connects MVC matchers with requestMatchers, Spring MVC endpoint mappings, path variables, RequestMatcher, regex matchers, authorization, and CSRF protection.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Security in Action, Second Edition. The section links point to the parts of the book it draws on.