【问题标题】:Difference between antMatcher and mvcMatcherantMatcher 和 mvcMatcher 的区别
【发布时间】:2018-11-05 06:31:37
【问题描述】:

HttpSecurity 的antMatcher() 和mvcMatcher() 函数有什么区别?

谁能解释一下什么时候使用它们?

【问题讨论】:

    标签: spring spring-security


    【解决方案1】:

    正如official documentation 中所述,该方法的签名明确表示 -

    antMatcher(String antPattern) - 允许将 HttpSecurity 配置为仅在匹配提供的 ant 模式时调用。

    mvcMatcher(String mvcPattern) - 允许将 HttpSecurity 配置为仅在匹配提供的 Spring MVC 模式时调用。

    通常mvcMatcher 比antMatcher 更安全。举个例子:

    • antMatchers("/secured") 仅匹配精确 /secured URL
    • mvcMatchers("/secured") 匹配 /secured 以及 /secured/、/secured.html、/secured.xyz

    因此更通用,也可以处理一些可能的配置错误。

    mvcMatcher 使用 Spring MVC 用于匹配的相同规则(使用 @RequestMapping 注释时)。

    如果当前请求不会被 Spring MVC 处理,则将使用使用该模式作为 ant 模式的合理默认值。 Source

    可以补充一点,mvcMatchers API(自 4.1.1 起)比antMatchers API(自 3.1 起)更新。

    【解决方案2】:

    AntMatcher() 是 Ant 样式路径模式的实现。此映射代码的一部分是从 Apache Ant 借来的。

    MvcMatcher() 使用 Spring MVC 的 HandlerMappingIntrospector 来匹配路径并提取变量。

    所以它们都实现了RequestMatcher 接口,但在底层使用了不同的表达语言。

    【讨论】:

      【解决方案3】:
      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") ...
        }
      }
      

      【讨论】:

      • JFYI 好像忘记添加示例了。
      猜你喜欢
      • 2019-05-27
      • 2013-08-07
      • 2011-10-20
      • 2020-01-23
      • 1970-01-01
      • 1970-01-01
      • 2016-06-23
      • 2021-04-21
      • 2014-10-09
      相关资源
      最近更新 更多