本文介绍了Spring Security @PreAuthorize 基于自定义布尔属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个应用程序,用户可以在其中输入自定义角色名称和权限.例如,用户可以创建一个名为Human Resources
"的角色,该角色具有以下属性:
I have an application where the user enters custom roles name and privileges.Example, the user can create a role named "Human Resources
" that has the following properties :
showDashboard = true;
showSuppliers = false;
showEmployees = true;
我想根据 showSuppliers
属性限制 getSuppliers
服务.
I want to restrict getSuppliers
service based on the showSuppliers
property.
@PreAuthorize("WHEN showSuppliers IS TRUE")
public Page<Supplier> getSuppliers();
角色实体:
@Entity
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
@GenericGenerator(name = "native", strategy = "native")
private Long id;
private String name;
private boolean showDashboard;
private boolean showSuppliers;
private boolean showEmployees;
}
推荐答案
您可以在 PreAuthorize
表达式中引用 bean.首先这个bean/组件:
You can reference a bean in the PreAuthorize
expression. First this bean/component:
@Component("authorityChecker")
public class AuthorityChecker {
public boolean canShowSuppliers(Authentication authentication) {
for (Authority authority : authentication.getAuthorites()) {
Role role = (Role)authority; // may want to check type before to avoid ClassCastException
if (role.isShowSuppliers()) {
return true;
}
}
return false;
}
}
对此的注释将是:
@PreAuthorize("@authorityChecker.canShowSuppliers(authentication)")
public Page<Supplier> getSuppliers();
它将当前用户的 Authentication 对象传递给上面的 bean/组件.
It will pass the current user's Authentication object to the bean/component above.
这篇关于Spring Security @PreAuthorize 基于自定义布尔属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!