【问题标题】:How to use spatie permission middleware in Laravel?如何在 Laravel 中使用 spatie 权限中间件?
【发布时间】:2021-06-29 09:00:34
【问题描述】:

我正在使用 Laravel 8 和 Spatie 角色和权限。每个操作的权限都可以正常工作。但是,如果我将 delete action 权限分配给子管理员,但我直接从 URL middlware 中点击 create action 无法停止操作,因为用户没有创建权限。

 public function __construct(CustomerInterface $customerInterface)
{
    $this->customerInterface = $customerInterface;
    $this->middleware(['permission:create_customer|delete_customer|edit_customer|chnage_customer_status']);
}

我在构造函数中使用上述中间件。我该如何解决这个问题。

【问题讨论】:

    标签: laravel laravel-permission


    【解决方案1】:

    据我从documentation 得知,当您使用具有多个权限的permission 中间件时,如果至少签出一个权限,它将让请求继续进行。

    您需要的是基于方法的授权,为此,Laravel 使用policies,默认情况下您可以为常用方法编写单独的授权。 (索引、存储、更新、显示等)

    假设您只允许用户使用store 方法,前提是他们拥有create_customer 权限,您的策略将如下所示:

        /**
         * Determine whether the user can create models.
         *
         * @param User $user
         * @return mixed
         */
        public function create(User $user)
        {
            return $user->can('create_customer');
        }
    

    然后在您的控制器中,放置authorizeResource 函数,它将默认策略方法与您的默认资源控制器方法相关联:

        public function __construct(CustomerInterface $customerInterface)
        {
            $this->customerInterface = $customerInterface;
            $this->authorizeResource(Customer::class); // assuming your model name is Customer
        }
    

    或者,您可以编写自己的自定义策略方法并通过$this->authorize 方法使用它们,该方法在here 中进一步记录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 2019-12-20
      相关资源
      最近更新 更多