【发布时间】:2018-11-05 06:31:37
【问题描述】:
HttpSecurity 的antMatcher() 和mvcMatcher() 函数有什么区别?
谁能解释一下什么时候使用它们?
【问题讨论】:
HttpSecurity 的antMatcher() 和mvcMatcher() 函数有什么区别?
谁能解释一下什么时候使用它们?
【问题讨论】:
正如official documentation 中所述,该方法的签名明确表示 -
antMatcher(String antPattern)- 允许将HttpSecurity配置为仅在匹配提供的 ant 模式时调用。
mvcMatcher(String mvcPattern)- 允许将HttpSecurity配置为仅在匹配提供的 Spring MVC 模式时调用。
通常mvcMatcher 比antMatcher 更安全。举个例子:
antMatchers("/secured") 仅匹配精确 /secured URLmvcMatchers("/secured") 匹配 /secured 以及 /secured/、/secured.html、/secured.xyz
因此更通用,也可以处理一些可能的配置错误。
mvcMatcher 使用 Spring MVC 用于匹配的相同规则(使用 @RequestMapping 注释时)。
如果当前请求不会被 Spring MVC 处理,则将使用使用该模式作为 ant 模式的合理默认值。 Source
可以补充一点,mvcMatchers API(自 4.1.1 起)比antMatchers API(自 3.1 起)更新。
AntMatcher() 是 Ant 样式路径模式的实现。此映射代码的一部分是从 Apache Ant 借来的。
MvcMatcher() 使用 Spring MVC 的 HandlerMappingIntrospector 来匹配路径并提取变量。
所以它们都实现了RequestMatcher 接口,但在底层使用了不同的表达语言。
【讨论】:
antMatcher("/users/**") matches any path starting with /users
antMatchers("/users") matches only the exact /users URL
mvcMatchers("/users") matches /users, /users/, /users.html
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/users/movie/**") // matches any path starting with /users/movie
.hasRole("ADMIN") ...
}
}
【讨论】: