java - Spring Security @PreAuthorize 基于自定义 boolean 属性值

标签 java spring spring-boot spring-security user-roles

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

关于java - Spring Security @PreAuthorize 基于自定义 boolean 属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53248269/

相关文章:

Spring Boot 2 - 基于过滤器的 JWT Spring Security 实现中的 403 而不是 401

java - 如何将xml文件数据添加到ArangoDb中?

java - Spring + RabbitMQ Exponential Backoff with RetryTemplate 无响应

java - 上下文初始化失败 org.springframework.beans.factory.BeanCreationException : Error creating bean with name defined in class path resource

java - Spring OAuth2 client_credentials 与预身份验证用户相结合

java - JPQL 检查大于小于今天@Query 注解中的日期

java - 设置新 SmartGWT 主题时出现问题 'Tahoe'

java - AWS/Java : How to Get EC2 Instances From AWS Java API

java - JFreeChart 极坐标图自定义 X 标签

java - 使用 `jsonPath` 过滤掉包含空数组的元素的表达式