Matchers Methods#
Spring Security offers 3 types of matchers methods to configure endpoints security:
- MVC matchers
- Ant matchers
- Regex matchers
MVC Matchers#
-
MvcMatcher()method uses Spring MVC's HandlerMappingIntrospector to match the path and extract variables.mvcMatchers(HttpMethod method, String... patterns: we can specify both the HTTP method and path pattern to configure restrictions
-1 2 3 4
http.authorizeRequests() .mvcMatchers(HttpMethod.POST, "/example").authenticated() .mvcMatchers(HttpMethod.GET, "/example").permitAll() .anyRequest().denyAll();mvcMatchers(String... patterns): we can specify only path pattern to configure restrictions and all the HTTP methods will be allowed.1 2 3
http.authorizeRequests() .mvcMatchers("/profile/edit/**").authenticated() .anyRequest().permitAll();
- Indicates any number of paths. For example ,
/x/**/zwill match both/x/y/zand/x/y/abc/z.- Single
*indicates single path. For example/x/*/zwill match/x/y/z,/x/abc/zbut not/x/y/abc/z.
Ant Matchers#
-
ANT matchersis an implementation of Ant-style path patterns. Part of this mapping code has been kindly borrowed from Apache Ant.antMatchers(HttpMethod method, String... patterns): we can specify both the HTTP method and path pattern to configure restrictions
1 2 3 4
http.authorizeRequests() .antMatchers(HttpMethod.POST, "/example").authenticated() .antMatchers(HttpMethod.GET, "/example").permitAll() .anyRequest().denyAll();antMatchers(String...patterns): we can specify only path pattern to configure restrictions and all the HTTP methods will be allowed.
-1 2 3
http.authorizeRequests() .antMatchers("/profile/edit/**").authenticated() .anyRequest().permitAll();antMatchers(HttpMethod method): we can specify only HTTP method ignoring path pattern to configure restrictions. This is same asantMatchers(httpMethod, "/**")1 2 3
http.authorizeRequests() .antMatchers(HttpMethod.POST).authenticated() .anyRequest().permitAll();
- Generally
mvcMatcheris more secure thanantMatcher. As an exampleantMatchers("/secured")matches only exact/securedURLmvcMatchers("/secured")matches/securedas well as/secured/,/secured.html,/secured.xyz
Regex Matchers#
-
Regexescan be used to represent any format of a string, so they offer unlimited possibilities for this matter.regexMatchers(HttpMethod method, String regex): we can specify both the HTTP method and path regex to configure restrictions,
1 2 3
http.authorizeRequests() .regexMatchers(HttpMethod.GET,".*/(en\vn\ch)").authenticated() .anyRequest().denyAll();regexMatchers(String regex): we can specify only path regex to configure restrictions and all the HTTP methods will be allowed.
1 2 3
http.authorizeRequests() .regexMatchers(".*/(en\vn\ch)").authenticated() .anyRequest().denyAll();