leonvr
120
2
Laravel

Policy not working

Posted 1 month ago by leonvr

I am trying to implement a policy on my Wishlist resource, but I always get "This action is unauthorized." even if my policy always returns true. What am I doing wrong?

WishlistPolicy:
<?php

namespace App\Policies;

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

class WishlistPolicy
{
    use HandlesAuthorization;

    //Determine whether the user can maintain the wishlist.
    public function maintain(User $user, Wishlist $wishlist)
    {
        return true;
        //return $user->type == 'beheerder' && $user->id === $wishlist->user_id;
    }

}

AuthServiceProvider:

    protected $policies = [
        // 'App\Model' => 'App\Policies\ModelPolicy',
        'App\Models\Wishlist::class' => 'App\Policies\WishlistPolicy::class',
    ];

api.php:

Route::middleware(['auth:api', 'verified', 'can:maintain,wishlist'])->group(function () {
    Route::apiResource('wishlists', 'WishlistController');
});

get request with Insomnia: http://laravelapi1.test/api/wishlists/21

result:

  "message": "This action is unauthorized.",
  "exception": "Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException",
  "file": "/home/vagrant/code/laravelapi1/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php",
  "line": 202,

Please sign in or create an account to participate in this conversation.