2

我想在授权失败时回复自定义消息。我已经覆盖了 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);
}
4

0 回答 0