Spring Security4 - 路径Uri中的 Ant 风格

1. 前言

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

2. Ant风格

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

3. Ant 通配符

Ant中的通配符有三种:

  • ?匹配任何单个字符

  • *匹配0或者任意数量的字符

  • **匹配0或者更多的目录

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

3.1 Ant 通配符示例

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 中 我们在控制器中写如下接口:

1
2
3
4
5
6
7
8
9
10
/**
* 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 中的你可以通过如下配置进行路由权限访问控制:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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 通配符来控制了资源的访问权限。

5. 总结

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

转载自@felord.cn