Spring 安全性 @PreAuthorize 基于自定义布尔值 属性

Spring Security @PreAuthorize based on custom boolean property value

我有一个应用程序,用户可以在其中输入自定义角色名称和权限。 例如,用户可以创建一个名为“Human Resources”的角色,该角色具有以下属性:

showDashboard = true;
showSuppliers = false;
showEmployees = true;

我想限制 getSuppliers 基于 showSuppliers 属性 的服务。

@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/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();

它将当前用户的身份验证对象传递给上面的bean/component。