其实老早就见过了,并且用的很多,比如spring中的扫描包路径,但是最近学习SpringSecurity中出现地十分频繁,所以决定撸下来,涨点经验。
实现spring-security的配置HttpSecurity
时,我们不可避免地需要添加一些Ant风格的URL,如下所示:
//spring-security的Java配置
@EnableWebSecurity
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()
.and()
.csrf().disable()//默认开启,这里先显式关闭
.formLogin()
.loginPage("/login.html")//表单登录页面
.loginProcessingUrl("/login")
.usernameParameter("username")//表单中用户名的变量名
.passwordParameter("password")//表单中密码的变量名
.successForwardUrl("/success.html")
.failureForwardUrl("/error.html")
//.defaultSuccessUrl()//如果用户没有访问受保护的页面,默认跳转到页面
//.failureUrl()
//.failureHandler(AuthenticationFailureHandler)
//.successHandler(AuthenticationSuccessHandler)
//.failureUrl("/login?error")
.permitAll();//允许所有用户都有权限访问登录页面
}
}
其中的antMatchers()中就是ant风格。
阿帕奇Ant样式的路径有三种通配符匹配方法,利用它们可以组合出多种路径模式:
Wildcard | Description |
---|---|
? | 匹配任意单字符 |
* | 匹配0或者任意数量的字符,不包含/ |
** | 匹配0或者更多数量的目录,不包含/ |
Ant风格路径匹配实例:
Path | Description |
---|---|
/app/*.x | 匹配(Matches)app路径下所有.x文件 |
/app/p?ttern | 匹配(Matches) /app/pattern 和 /app/pXttern,但是不包括/app/pttern |
/**/example | 匹配项目根路径下 /project/example, /project/foow/example, 和 /example |
/app/**/dir/file. | 匹配(Matches) /app/dir/file.jsp, /app/foo/dir/file.html,/app/foo/bar/dir/file.pdf, 和 /app/dir/file.java |
/**/*.jsp | 匹配项目根路径下任何的.jsp 文件 |
需要注意的是,路径匹配遵循最长匹配原则(has more characters),例如/app/dir/file.jsp
符合/**/*.jsp
和/app/dir/*.jsp
两个路径模式,那么最终就是根据后者来匹配。