Laravel 6.x 授权后未调用策略(无中间件)

Laravel 6.x Policy not being called after authorize (No Middleware)

我在使用 Laravel 6 政策时遇到了一些问题。我一直收到 403 unauthorized 请求,即使它应该是一个未经身份验证的请求。

文件:

api.php

Route::prefix('v2')
  ->group(function () {
        Route::prefix('agencies')->group(function () {
            Route::post('/', 'Api\AgencyController@store');
        });
    }

AgencyController.php

<?php

namespace App\Http\Controllers\Api;

use App\Entities\Agency;

class AgencyController extends Controller {
    public function store(AgencyRequest $request)
    {
        $this->authorize('create', Agency::class);

        // Code that is never executed
    }
}

AgencyPolicy.php

class AgencyPolicy
{
    public function create(User $user)
    {
        \Log::info('hello?'); // This Log is never executed
        return true;
    }
}

AuthServiceProvider.php

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        \App\Entities\Agency::class => \App\Policies\AgencyPolicy::class,
        // Other policies
    ];

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

        Gate::before(function ($user) {
            if ($user->hasRole(SuperAdmin::ROLE_NAME)) {
                return true;
            }
        });

        Passport::routes(null,  ['prefix' => 'api/oauth']);
    }
}

我的代码与文档相同,但我总是收到 403 未经授权的消息,而且我一直无法理解发生了什么。我们将不胜感激。

谢天谢地,作为 lagbox ,答案在文档中,其中指出:

By default, all gates and policies automatically return false if the incoming HTTP request was not initiated by an authenticated user. However, you may allow these authorization checks to pass through to your gates and policies by declaring an "optional" type-hint or supplying a null default value for the user argument definition:

因此,我的问题将通过在 AgencyPolicy.php:

中使用 ?User 来解决
class AgencyPolicy
{
    public function create(?User $user)
    {
        return true;
    }
}

这解决了问题。