Home > Software engineering >  Laravel UserPolicy always returns 403 no matter what
Laravel UserPolicy always returns 403 no matter what

Time:02-27

I have the following policy called UserPolicy. I want only admin users to access/edit the users data, even though I have set the return value to true(for testing) I still get 403 response no matter what.


namespace App\Policies;

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

class UserPolicy
{
    use HandlesAuthorization;

    public function viewAny(User $user)
    {
        // return $user->admin();
        return true;
    }
}

I have registered the policy as follows


namespace App\Providers;

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

use App\Models\Auth\User;
use App\Policies\UserPolicy;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        User::class => UserPolicy::class,
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        //
    }
}

The following code is how I use it in the controller

 if (Gate::denies('viewAny')) {
            return response('Not Authorized!', 403);
        } 

CodePudding user response:

You should use authorize() method in your controller and pass User class as the second parameter. It will point the request to the targeted policy.

authorize() method is by default provided by Illuminate\Foundation\Auth\Access\AuthorizesRequests trait in your base controller.

Your controller could be like below:

try {
    $this->authorize('viewAny', User::class);
} catch (AuthorizationException $e) {
    return response('Not Authorized!', 403);
}
  • Related