我想在授权失败时回复自定义消息。 我已经覆盖了Policy类中的方法,但它没有返回自定义消息。
策略:
class PostPolicy
{
use HandlesAuthorization;
/**
* Determine if user can view post
* @param User $user
* @param Post $post
* @return bool
*/
public function view(User $user, Post $post)
{
return $user
->posts()
->where('post_id', $post->id)
->exists();
}
/**
* [deny description]
* @return [type] [description]
*/
protected function deny()
{
return response()->json([
'message' => 'My custom unauthorized message'
], 401);
}
}
在PostController中实现:
...
public function show(Post $post)
{
$this->authorize('view', $post);
...
}
响应仍然返回HandlesAuthorization
特征中定义的内容,即:
protected function deny($message = 'This action is unauthorized.')
{
throw new AuthorizationException($message);
}