Spring Security 实战干货:路径Uri中的 Ant 风格


1. 前言

我们经常在读到一些文章会遇到uri 支持 Ant 风格 ,而且这个东西在 Spring MVCSpring Security 中经常被提及。这到底是什么呢?今天我们来学习了解一下。这对我们学习 Spring MVCSpring Security 十分必要。

2. Ant 风格

说白了 Ant 风格就是一种路径匹配表达式。主要用来对uri的匹配。其实跟正则表达式作用是一样的,只不过正则表达式适用面更加宽泛,Ant仅仅用于路径匹配。

3. Ant 通配符

Ant 中的通配符有三种:

  • ? 匹配任何单字符
  • * 匹配0或者任意数量的 字符
  • ** 匹配0或者更多的 目录

这里注意了单个* 是在一个目录内进行匹配。 而** 是可以匹配多个目录,一定不要迷糊。

3.1 Ant 通配符示例

通配符 示例 说明
? /ant/p?ttern 匹配项目根路径下 /ant/pattern/ant/pXttern,但是不包括/ant/pttern
* /ant/*.html 匹配项目根路径下所有在ant路径下的.html文件
* /ant/*/path /ant/path/ant/a/path/ant/bxx/path 都匹配,不匹配 /ant/axx/bxx/path
** /ant/**/path /ant/path/ant/a/path/ant/bxx/path/ant/axx/bxx/path都匹配

3.2 最长匹配原则

从 3.1 可以看出 *** 是有冲突的情况存在的。为了解决这种冲突就规定了最长匹配原则(has more characters)。 一旦一个uri 同时符合两个Ant匹配那么走匹配规则字符最多的。为什么走最长?因为字符越长信息越多就越具体。比如 /ant/a/path 同时满足 /**/path/ant/*/path 那么走/ant/*/path

4. Spring MVC 和 Spring Security 中的 Ant 风格

接下来我们来看看 Spring MVCSpring Security 下的 Ant风格。

4.1 Spring MVC 中的 Ant 风格

这里也提一下在 Spring MVC 中 我们在控制器中写如下接口:

     /**
      * ant style test.
      *
      * @return the string
      */
     @GetMapping("/?ant")
     public String ant() {
 
         return "ant";
     }

你使用任意合法uri字符替代? 发现都可以匹配,比如/bant 。 还有Spring MVC 的一些 过滤器注册、格式化器注册都用到了 Ant 风格。

4.2 Spring Security 中的 Ant 风格

Spring SecurityWebSecurityConfigurerAdapter 中的你可以通过如下配置进行路由权限访问控制:

  public class SecurityConfig extends WebSecurityConfigurerAdapter {
  
      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
          authenticationManagerBuilder.inMemoryAuthentication().withUser("admin").password("admin").roles("USER");
      }
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.authorizeRequests()
                  //放行静态资源 首页
                  .antMatchers("/index.html","/static/**").permitAll()
                  .anyRequest().authenticated();
      }
  }
 

上面 Spring Security 的配置中在 antMatchers 方法中通过 Ant 通配符来控制了资源的访问权限。 后面我也会出相关的教程,敬请关注公众号:Felordcn 和个人博客:https://felord.cn

5. 总结

Ant 风格整体东西不多,也很好理解。 很多关于uri 的配置、路由匹配、处理都用到了 Ant 风格 。对于 Web 开发人员来说是必须掌握的技能之一。

关注公众号:Felordcn获取更多资讯

个人博客:https://felord.cn

posted @ 2019-10-15 13:12  码农小胖哥  阅读(754)  评论(0编辑  收藏  举报