基于自定义布尔属性值的 Spring Security @PreAuthorize

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

}


交互式爱情
浏览 307回答 1
1回答

ITMISS

您可以在PreAuthorize表达式中引用 bean 。首先这个bean/组件:@Component("authorityChecker")public class AuthorityChecker {&nbsp; &nbsp; public boolean canShowSuppliers(Authentication authentication) {&nbsp; &nbsp; &nbsp; &nbsp; for (Authority authority : authentication.getAuthorites()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Role role = (Role)authority; // may want to check type before to avoid ClassCastException&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (role.isShowSuppliers()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }}对此的注释将是:@PreAuthorize("@authorityChecker.canShowSuppliers(authentication)")public Page<Supplier> getSuppliers();它将当前用户的 Authentication 对象传递给上面的 bean/component。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java