简体   繁体   English

Laravel政策访客用户

[英]Laravel Policy Guest User

I have the following Policy: 我有以下政策:

<?php

namespace App\Policies;

use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class EventPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view the whole model.
     *
     * @param User $user
     * @return boolean
     */
    public function list(?User $user) {
        return true;
    }

}

AuthServiceProvider contains the correct binding: AuthServiceProvider包含正确的绑定:

protected $policies = [
    Event::class => EventPolicy::class,
];

In my controller: 在我的控制器中:

public function index() {
    $this->authorize('list');
    return $this->repository->paginate();
}

This return a 403 Forbidden response: 这返回403 Forbidden响应:

This action is unauthorized.

Laravel documentation states that you can make the user declaring the User optional or setting a default null value. Laravel文档声明您可以让用户声明User可选或设置默认null值。 I have tried both to no avail. 我试过两个都无济于事。

I'm running v5.8 我正在运行v5.8

Any ideas? 有任何想法吗?

This is probably an internal misbehavior of Laravel because the logic is somehow broken (it is just an assumption). 这可能是Laravel的内部不端行为,因为逻辑在某种程度上被打破了(这只是一个假设)。

In this particular case, you shouldn't add any authorization policy for listing, since everyone is allowed to see the results. 在这种特殊情况下,您不应为列表添加任何授权策略,因为每个人都可以查看结果。

So you should simply do it like: 所以你应该这样做:

public function index()
{
    return $this->repository->paginate();
}

Define policies only if the users should be actually authorized to do something. 仅在用户实际上有权执行某些操作时才定义策略。

Later edit : is it possible that in the service provider you imported the Event class from Laravel instead of the Event model? 稍后编辑 :是否有可能在服务提供商中从Laravel而不是事件模型导入了Event类?

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

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