Spring Security @PreAuthorize 基于自定义布尔属性值[关闭]

2024-04-22

我有一个应用程序,用户在其中输入自定义角色名称和权限。 例如,用户可以创建一个名为“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/组件:

@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/组件。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring Security @PreAuthorize 基于自定义布尔属性值[关闭] 的相关文章

随机推荐