laravel
laravel copied to clipboard
Support policy responses to allow developers to return custom messages when authorization fails
At the moment in our authorizer class we do this:
return $this->gate->check(
'view',
$model
);
An improvement would be to support Policy Responses so that the developer can return authorization messages from their policy.
To do that, the code would be something like this:
$response = $this->gate->inspect(
'view',
$model
);
if ($response->message()) {
$response->authorize();
}
return $response->allowed();
I.e. if the authorization response has a message, calling the authorize()
method on the response will throw an authorization exception with that message if the authorization has failed.
When returning the Response::deny()
function from within a policy it appears not to be respected by this package at the moment.
If I provide a code, e.g. Response::deny(code: 404) from my policy the user still gets a 403.
I think I've traced it back to the Authorizer class in that it runs check and not inspect (https://laravel.com/docs/9.x/authorization#policy-responses).
My current workaround for this is just to abort(404)
but it seems a bit ugly and with the introduction of this - https://github.com/laravel/framework/pull/43097 - it seems there is also good reason to use the Response class instead of abort.
Further there is now a function to denyAsNotFound()
which also sets the status for you.