昨天有個粉絲加了我,問我如何實作類似shiro的資源權限運算式的訪問控制,我以前有一個小框架用的就是shiro,權限控制就用了資源權限運算式,所以這個東西對我不陌生,但是在Spring Security中我并沒有使用過它,不過我認為Spring Security可以實作這一點,是的,我找到了實作它的方法,
資源權限運算式
說了這么多,我覺得應該解釋一下什么叫資源權限運算式,權限控制的核心就是清晰地表達出特定資源的某種操作,一個格式良好好的權限宣告可以清晰表達出用戶對該資源擁有的操作權限,
通常一個資源在系統中的標識是唯一的,比如User用來標識用戶,ORDER標識訂單,不管什么資源大都可以歸納出以下這幾種操作

在 shiro權限宣告通常對上面的這種資源操作關系用冒號分隔的方式進行表示,例如讀取用戶資訊的操作表示為USER:READ,甚至還可以更加細一些,用USER:READ:123表示讀取ID為123的用戶權限,
資源操作定義好了,再把它和角色關聯起來不就是基于RBAC的權限資源控制了嗎?就像下面這樣:

這樣資源和角色的關系可以進行CRUD操作進行動態系結,
Spring Security中的實作
資源權限運算式動態權限控制在Spring Security也是可以實作的,首先開啟方法級別的注解安全控制,
/**
* 開啟方法安全注解
*
* @author felord.cn
*/
@EnableGlobalMethodSecurity(prePostEnabled = true,
securedEnabled = true,
jsr250Enabled = true)
public class MethodSecurityConfig {
}
MethodSecurityExpressionHandler
MethodSecurityExpressionHandler 提供了一個對方法進行安全訪問的門面擴展,它的實作類DefaultMethodSecurityExpressionHandler更是提供了針對方法的一系列擴展介面,這里我總結了一下:

這里的PermissionEvaluator正好可以滿足需要,
PermissionEvaluator
PermissionEvaluator 介面抽象了對一個用戶是否有權限訪問一個特定的領域物件的評估程序,
public interface PermissionEvaluator extends AopInfrastructureBean {
boolean hasPermission(Authentication authentication,
Object targetDomainObject, Object permission);
boolean hasPermission(Authentication authentication,
Serializable targetId, String targetType, Object permission);
}
這兩個方法僅僅引數串列不同,這些引數的含義為:
authentication當前用戶的認證資訊,持有當前用戶的角色權限,targetDomainObject用戶想要訪問的目標領域物件,例如上面的USER,permission這個當前方法設定的目標領域物件的權限,例如上面的READ,targetId這種是對上面targetDomainObject的具體化,比如ID為123的USER,我覺得還可以搞成租戶什么的,targetType是為了配合targetId,
第一個方法是用來實作
USER:READ的;第二個方法是用來實作USER:READ:123的,
思路以及實作
targetDomainObject:permission不就是USER:READ的抽象嗎?只要找出USER:READ對應的角色集合,和當前用戶持有的角色進行比對,它們存在交集就證明用戶有權限訪問,借著這個思路胖哥實作了一個PermissionEvaluator:
/**
* 資源權限評估
*
* @author felord.cn
*/
public class ResourcePermissionEvaluator implements PermissionEvaluator {
private final BiFunction<String, String, Collection<? extends GrantedAuthority>> permissionFunction;
public ResourcePermissionEvaluator(BiFunction<String, String, Collection<? extends GrantedAuthority>> permissionFunction) {
this.permissionFunction = permissionFunction;
}
@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
//查詢方法標注對應的角色
Collection<? extends GrantedAuthority> resourceAuthorities = permissionFunction.apply((String) targetDomainObject, (String) permission);
// 用戶對應的角色
Collection<? extends GrantedAuthority> userAuthorities = authentication.getAuthorities();
// 對比 true 就能訪問 false 就不能訪問
return userAuthorities.stream().anyMatch(resourceAuthorities::contains);
}
@Override
public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
//todo
System.out.println("targetId = " + targetId);
return true;
}
}
第二個方法沒有實作,因為兩個差不多,第二個你可以想想具體的使用場景,
配置和使用
PermissionEvaluator 需要注入到Spring IoC,并且Spring IoC只能有一個該型別的Bean:
@Bean
PermissionEvaluator resourcePermissionEvaluator() {
return new ResourcePermissionEvaluator((targetDomainObject, permission) -> {
//TODO 這里形式其實可以不固定
String key = targetDomainObject + ":" + permission;
//TODO 查詢 key 和 authority 的關聯關系
// 模擬 permission 關聯角色 根據key 去查 grantedAuthorities
Set<SimpleGrantedAuthority> grantedAuthorities = new HashSet<>();
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
return "USER:READ".equals(key) ? grantedAuthorities : new HashSet<>();
});
}
接下來寫個介面,用@PreAuthorize注解標記,然后直接用hasPermission('USER','READ')來靜態系結該介面的訪問權限運算式:
@GetMapping("/postfilter")
@PreAuthorize("hasPermission('USER','READ')")
public Collection<String> postfilter(){
List<String> list = new ArrayList<>();
list.add("felord.cn");
list.add("碼農小胖哥");
list.add("請關注一下");
return list;
}
然后定義一個用戶:
@Bean
UserDetailsService users() {
UserDetails user = User.builder()
.username("felord")
.password("123456")
.passwordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder()::encode)
.roles("USER")
.authorities("ROLE_ADMIN","ROLE_USER")
.build();
return new InMemoryUserDetailsManager(user);
}
接下來肯定是正常能夠訪問介面的,當你改變了@PreAuthorize中運算式的值或者移除了用戶的ROLE_ADMIN權限,再或者USER:READ關聯到了其它角色等等,都會回傳403,
留給你去測驗的
你可以看看注解改成這樣會是什么效果:
@PreAuthorize("hasPermission('1234','USER','READ')")
還有這個:
@PreAuthorize("hasPermission('USER','READ') or hasRole('ADMIN')")
或者讓targetId動態化:
@PreAuthorize("hasPermission(#id,'USER','READ')")
public Collection<String> postfilter(String id){
}
關注公眾號:Felordcn 獲取更多資訊
個人博客:https://felord.cn
|
博主:碼農小胖哥 出處:felord.cn 本文著作權歸原作者所有,不可商用,轉載需要宣告出處,否則保留追究法律責任的權利,如果文中有什么錯誤,歡迎指出,以免更多的人被誤導, |
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/458644.html
標籤:其他
