Java 基于自定义布尔属性值的Spring Security@PreAuthorize
我有一个用户输入自定义角色名称和权限的应用程序。 例如,用户可以创建名为“Java 基于自定义布尔属性值的Spring Security@PreAuthorize,java,spring,spring-boot,spring-security,user-roles,Java,Spring,Spring Boot,Spring Security,User Roles,我有一个用户输入自定义角色名称和权限的应用程序。 例如,用户可以创建名为“Human Resources”的角色,该角色具有以下属性: showDashboard = true; showSuppliers = false; showEmployees = true; 我想基于showSuppliers属性限制getSuppliers服务 @PreAuthorize("WHEN showSuppliers IS TRUE") public Page<Supplier> getSup
Human Resources
”的角色,该角色具有以下属性:
showDashboard = true;
showSuppliers = false;
showEmployees = true;
我想基于showSuppliers
属性限制getSuppliers
服务
@PreAuthorize("WHEN showSuppliers IS TRUE")
public Page<Supplier> getSuppliers();
您可以在
预授权
表达式中引用bean。首先,这个bean/组件:
@组件(“authorityChecker”)
公共类AuthorityChecker{
公共供应商(认证){
for(授权:authentication.getAuthorites()){
Role Role=(Role)authority;//可能需要先检查类型,以避免ClassCastException
if(role.isShowSuppliers()){
返回true;
}
}
返回false;
}
}
对此的注释将是:
@预授权(@authorityChecker.canShowSuppliers(身份验证)”)
公共页面getSuppliers();
它会将当前用户的身份验证对象传递给上面的bean/组件。我已经根据您的回答创建了一个组件,该组件从经过身份验证的用户返回整个角色对象,然后我检查@PreAuthorize上的每个属性。
@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;
}