简体   繁体   English

如何在 Laravel 中使用 spatie 权限中间件?

[英]How to use spatie permission middleware in Laravel?

I am using Laravel 8 and Spatie Role and Permission.我正在使用 Laravel 8 和 Spatie 角色和权限。 Permission for each action working fine.每个操作的权限都可以正常工作。 But if i assign delete action permission to sub admin but I hit create action directly from URL middlware can not stop action as user have not create permission.但是,如果我将删除操作权限分配给子管理员,但我直接从 URL middlware 中点击创建操作,则由于用户没有创建权限,因此无法停止操作。

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

I am using above middleware in constructor.我在构造函数中使用上述中间件。 How can i Solve this issue.我该如何解决这个问题。

From what I can tell from the documentation , when you use the permission middleware with multiple permissions, it will let the request proceed if at least one permission checks out.文档中我可以看出,当您使用具有多个权限的permission中间件时,如果至少有一个权限签出,它将让请求继续进行。

What you need is method-based authorization and for that, Laravel uses policies which by default lets you write separate authorization for common methods.您需要的是基于方法的授权,为此,Laravel 使用策略,默认情况下允许您为常用方法编写单独的授权。 (index, store, update, show, etc) (索引、存储、更新、显示等)

Let's say you let a user use the store method only if they have the create_customer permission, your policy will look something like this:假设您让用户仅在拥有create_customer权限的情况下使用store方法,您的策略将如下所示:

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

Then in your controller, you put the authorizeResource function which associates the default policy methods with your default resource controller methods:然后在 controller 中,放置authorizeResource function ,它将默认策略方法与默认资源 controller 方法相关联:

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

alternatively, you can write your own custom policy methods and use them via the $this->authorize method which is documented further here .或者,您可以编写自己的自定义策略方法并通过$this->authorize方法使用它们,该方法在此处进一步记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM