Laravel API 中的政策总是 403 未授权

Laravel Policies in API always 403 unauthorized

我尝试使用策略在 userController 中授权用户。我遵循了文档和一些教程,但它似乎仍然不起作用。

api.php

Route::resource('users', 'User\UserController', ['except' => ['create', 'edit']]);

UserController.php

namespace App\Http\Controllers\User;

use App\Http\Controllers\ApiController;
use Illuminate\Http\Request;
use App\User;
use App\Mail\UserCreated;
use App\Mail\UserEmailUpdated;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
class UserController extends ApiController
{
  public function __construct()
  {
    $this->middleware('can:view,user')->only('show');
    //$this->middleware('can:update,user')->only('update');
    //$this->middleware('can:delete,user')->only('destroy');
  }

    public function show(User $user)
    {
        //$this->authorize('view', $user);
        return $this->showOne($user);
    }

UserPolicy.php

namespace App\Policies;

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

class UserPolicy
{
    use HandlesAuthorization;

    public function view(User $user, User $model)
    {
        //return $user->id === $model->id
        return true;
    }
}

AuthServiceProvider.php

namespace App\Providers;

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

class AuthServiceProvider extends ServiceProvider
{

    protected $policies = [
        App\User::class => App\Policies\UserPolicy::class,
    ];

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

$this->middleware$this->authorize 都不起作用。如果我从控制器中删除策略授权,一切正常。此外,我在请求中从 Passport 传递了个人访问令牌,它也工作正常。如果我故意在策略文件中输入错误,则会抛出错误,因此策略似乎已正确连接到控制器。

您很可能在那里引用了错误的 类。 AutheServiceProvider 的命名空间声明为 App\Providers。除非另有别名,否则所有引用(不是完全限定的 Class 名称)都从声明的此命名空间引用。

App\User::class     would be   'App\Providers\App\User'

您需要为 App 命名空间设置别名,为这些 类 设置别名或使用它们的 FQCN。

use App;
...
App\User::class

use App\User;
...
User::class

\App\User::class

或者 - 次要(使用 FQCN 的字符串)

'App\User'