Everything looks okay. Are you sure that you're getting past the JWT Auth middleware, perhaps the 403 is coming from there?
Feb 14, 2019
3
Level 2
Policy gets never called
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');
});
}
}
Level 104
And you are getting a User model instance using route model binding?
Also, check that the before Gate is not causing the issue; it appears that it will block all non-Super Admins. It should return null rather than false if the user is not a Super Admin so that the other authorization classes can be checked.
Gate::before(function ($user, $ability) {
return $user->hasRole('super-admin') ? true : null;
});
10 likes
Please or to participate in this conversation.