Aiven
7 months ago

Policy gets never called

Posted 7 months ago by Aiven

I'm trying to use Policies to allow my users to view or update their own profiles. However my Policy Method gets never called, it returns always an 403 Forbidden Status Code. After searching for multiple hours across the internet I think the problem seems to be with JWT authentification.

Policy

namespace App\Policies;

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

class UserPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view the model.
     *
     * @param  \App\User  $user
     * @param  \App\User  $model
     * @return mixed
     */
    public function view(User $user, User $model)
    {
        return true;
        //return $user->can('view users') || $user->id === $model->id;
    }
}

Controller

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;

use App\User;
use App\Http\Requests\User as UserRequest;
use App\Http\Resources\User as UserResource;

class UserController extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(['jwt.auth']);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(User $user)
    {
        //return response()->json(auth()->user()->can('create'));   // Returns also 403
        $this->authorize('view', $user);

        return new UserResource($user);
    }

AuthServiceProvider

namespace App\Providers;

use App\User;
use App\Policies\UserPolicy;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

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();

        // Implicitly grant "Admin" role all permissions
        Gate::before(function ($user, $ability) {
            return $user->hasRole('super-admin');
        });
    }
}

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