Spring security config httpSecurity tips
在配置security时,由于版本更迭、加上本身配置项就很多,所以显得好像很复杂似的。
所以饭要一点一点吃嘛,先记下一个小知识点
hasRole() 和 hasAuthority()区别
下面是spring官方文档的一个例子
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests() 1
.antMatchers("/resources/**", "/signup", "/about").permitAll() 2
.antMatchers("/admin/**").hasRole("ADMIN") 3
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") 4
.anyRequest().authenticated() 5
.and()
// ...
.formLogin();
}
例子中用了hasRole() 表示有某种角色才可以访问
但是同时存在hasAuthority()方法
那么如何使用Role和Authority呢?
其实在Spring Security中,对于GrantedAuthority接口实现类来说是不区分是Role还是Authority,二者区别就是如果是hasAuthority判断,就是判断整个字符串,判断hasRole时,系统自动加上ROLE_到判断的Role字符串上,也就是说hasRole("ADMIN")和hasAuthority('ROLE_ADMIN')是相同的。
nice~ 👍
本作品采用《CC 协议》,转载必须注明作者和本文链接
本文由telami 创作,采用CC BY 3.0 CN协议 进行许可,可自由转载、引用,但需署名作者且注明。