Laravel 8 政策总是 returns "This action is unauthorized."

Laravel 8 Policy Always returns "This action is unauthorized."

我正在尝试为用户权限创建一个策略,所以我从数据库中检索用户权限并检查他是否能够执行此操作,但该策略总是 return 403:

类别控制器

我有这样的存储方法

    public function store(Request $request)
{
    $user = auth('sanctum')->user();
    if (!$user) {
        return $this->ApiResponse(401,null,'Can not do this action without login, Login and tray again',);
    }

    $ability = "create-category";
    $this->authorize('can',[$user,Category::class,$ability]);

    $request->validate( [
        'name' => 'required|unique:categories',
        'parent_id' => 'nullable|integer|exists:categories,id',
        ]);

    try {
        $project = Category::create($request->all());
        return $this->ApiResponse(Response::HTTP_CREATED, "category created successfully",null, $project);
    }catch (Exception $e) {
        return $this->ApiResponse(500, 'category can\'t be created try later');
    }
}

类别政策

我有这样的方法

public function can (User $user,Category $category,string $ability)
{
    $role = Role::with('permissions')->find($user->role_id);
    $permissions = $role->permissions;

    for ($i=0; $i<count($permissions); $i++) {
        $userPermissions[$i] = $permissions[$i]['name'];
    }
    if (in_array($ability, $userPermissions)) {
        return true;
    }
    return false;
}

AuthServiceProvider

 protected $policies = [
    Category::class => CategoryPolicy::class,

];

所以问题是什么??

我认为你只是混淆了一些参数

而不是

$this->authorize('can',[$user,Category::class,$ability]);

你可能想要

$this->authorize('create-category', Category::class);

或者,如果您不想通过 Auth::shouldUse() 的方式指定 sanctum 作为守卫,您可以使用以下内容:

$this->authorizeForUser(auth('sanctum')->user(), 'create-category', Category::class);

在您的政策中,您可以将论点简化为:

public function createCategory(User $user, Category $category)

如果您需要对 $ability 值进行任何检查,您可以使用 policy filters:


class CategoryPolicy
{
    /**
     * Perform pre-authorization checks.
     *
     * @param  \App\Models\User  $user
     * @param  string  $ability
     * @return void|bool
     */
    public function before(User $user, $ability)
    {
        if ($user->permissions->where('name', $ability)->isEmpty()) {
            return false;
        }
    }

    // ...