简体   繁体   English

授权策略 Laravel 5.3,仅返回“此操作未经授权”

[英]Authorization Policies Laravel 5.3, return only 'This action is unauthorized'

I'm learning about the policies in Laravel 5.3 and I'm having a problem, it always returns 'This action is unauthorized'.我正在了解 Laravel 5.3 中的政策,但遇到问题,它总是返回“此操作未经授权”。 what am I doing wrong?我究竟做错了什么? Here are the codes:以下是代码:

UserController.php用户控制器.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class UserController extends Controller
{
    public function index()
    {
        $this->authorize('list');

        $users = User::all();
        return $users;
    }
}

AuthServiceProvider.php AuthServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        'App\User' => 'App\Policies\UserPolicy',
    ];

    public function boot()
    {
        $this->registerPolicies();
    }
}

UserPolicy.php用户策略.php

<?php

namespace App\Policies;

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

class UserPolicy
{
    use HandlesAuthorization;

    public function list(User $user)
    {
      return true;
    }
}

You will need to add a second argument set to the model class when calling the authorize method, otherwise how will laravel know which list method/policy to check for authorization?调用authorize方法时,您需要向模型类添加第二个参数集,否则 Laravel 将如何知道要检查授权的list方法/策略? Other models could also have a list method/policy, hence the need for a second argument.其他模型也可能有一个list方法/策略,因此需要第二个参数。

$this->authorize('list', User::class);

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

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