pelmered's avatar

Authorization issues in Lumen 5.3

I've been using Policies in Lumen 5.2 and lower before, but now I wanted the use the new 5.3 (beta) version for the new project.

Everything has worked as expected so far, until I started to use Polices for permissions in the same way as I've done before. My Policy classes are never triggered. This is what I've been doing before in 5.2 and before:

    // In my controller:
        if (Gate::denies('read', $model)) {
            return $this->permissionDeniedResponse();
        }
    //I've also tried:
        $this->authorize('read', $model);
    //In boot in AuthServiceProvider.php
        Gate::policy(\My\Namespace\Models\Order::class,      Policies\OrderPolicy::class);

    //I've also tried this:

        Gate::define('read', function ($user, $post) {
            return $user->id == $post->user_id;
        });

This worked as expected in Lumen 5.2, but now with 5.3 the Policies are never triggered at all. Any ideas?

0 likes
4 replies
bobbybouwmann's avatar

Your code looks fine to me. I need a bit more context to figure out what's really going on!

Are you sure the service provider is loaded?

gperez78's avatar

Any news? I'm also trying this.

AuthServiceProvider

Gate::policy(User::class, \App\Policies\UserSelfPolicy::class);

UserController

$this->authorize('me', $user_id);

But my policy never gets called. Tried performing some dd inside it. Mthod just rhrows a 403 error.

<?php

namespace App\Policies;

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

class UserSelfPolicy
{
    use HandlesAuthorization;

    private $user;
    
    /**
     * Create a new policy instance.
     *
     * @return void
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

     /**
     * Determine if the given resource is self.
     *
     * @param  \App\User  $user
     * @return bool
     */
    public function me(int $user_id)
    {
        return $this->user->id === $user_id;
    }    
}
gperez78's avatar

Well, can't get policies to work, but using gates does work:

AuthServiceProvider

use Illuminate\Contracts\Auth\Access\Gate;
use Illuminate\Support\Facades\Auth;

...
{
    public function boot()
    {

        $this->app[Gate::class]->define('myself', function(User $user, int $user_id) {
            return $user->id === $user_id;
        });    
    }
}

UserController

$this->authorize('myself', $user_id);

Please or to participate in this conversation.