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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}
答案

您可以在PreAuthorize表达式中引用bean。首先这个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 /组件。

以上是关于Spring Security @PreAuthorize基于自定义布尔属性值[关闭]的主要内容,如果未能解决你的问题,请参考以下文章

Spring mvc / security:从spring security中排除登录页面

Spring Security:2.4 Getting Spring Security

没有 JSP 的 Spring Security /j_spring_security_check

Spring-Security

Spring Security 登录错误:HTTP 状态 404 - /j_spring_security_check

未调用 Spring Security j_spring_security_check