Search code examples
laravellaravel-passport

How to authorize user owns resource using API through middleware in Laravel?


I need to check if user is permitted to view resource. Request is sent by API and passes through auth:api middleware. I'm using Laravel 5.8

I tried to use middleware in route declaration like this:

Route::get('/user/{id}', 'UserController@get')->middleware('can:view,user')

or in method's controller code like this:

$user = Auth::guard('api')->user();
$this->authorize('view', $user, $anotherUserModel);

Each of these methods either lets user pass policy even it's hardcoded to stops user form achieving this or throws error:

{
    "message": "This action is unauthorized.",
    "exception": "Symfony\\Component\\HttpKernel\\Exception\\AccessDeniedHttpException",
    "file": "C:\\xampp\\htdocs\\laravelapitest\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Exceptions\\Handler.php",
    "line": 202,
    [...]
}

but I'm expecting that user should be stopped and response code should be 403


Solution

  • Can you please give this a try and let me know if it fixes your problem.

    Go to App\Exceptions folder and add the following at the top of the Handler.php file:

    use Illuminate\Auth\Access\AuthorizationException;
    

    add the following to $dontReport array in the same file:

    \Illuminate\Auth\Access\AuthorizationException::class,
    

    and the last step is to customize error response by adding the following code in the render function:

    if ($exception instanceof AuthorizationException) {
        return response()->json('unauthorized',403);
    }