【问题标题】:Laravel API give json response when got error This action is unauthorizedLaravel API 在收到错误时给出 json 响应此操作未经授权
【发布时间】:2017-04-29 19:11:06
【问题描述】:

我是 Laravel API 的新手。有一个更新功能,只允许用户更新自己的帖子。有效。当用户尝试更新其他用户的帖子时,它也可以正常工作,但会显示此图像的错误。实际上我希望它显示在响应 json 中。

我想显示这样的消息

{
"status": "error",
"message": "This action is unauthorized",
}

这是我的 PostController 代码。

public function update(Request $request, Post $post)
{

    $this->authorize('update', $post);    
//this will check the authorization of user but how to make if else statement, if the post belong to the user it will show this json below but if the post belong to other, it will show error message(response json) 


    $post->content = $request->get('content', $post->content);
    $post->save();

    return fractal()
        ->item($post)
        ->transformWith(new PostTransformer)
        ->toArray();

}

PostPolicy 的代码

public function update(User $user, Post $post)
 {
    return $user->ownsPost($post);
 }

这是用户模型的代码

public function ownsPost(Post $post)
{
    return Auth::user()->id === $post->user->id;
}

AuthServiceProvider 的代码

 protected $policies = [
        'App\Post' => 'App\Policies\PostPolicy',
];

希望任何人都可以帮助我。

【问题讨论】:

    标签: api if-statement jsonresponse


    【解决方案1】:

    我正在使用 Laravel 5.4

    app/Exceptions/Handler.php 类中,您可以像这样更改渲染函数

    public function render($request, Exception $exception)
    {
        $preparedException = $this->prepareException($exception);
    
        if ($preparedException instanceof HttpException) {
            return response(
                [
                    'message' => sprintf(
                        '%d %s',
                        $preparedException->getStatusCode(),
                        Response::$statusTexts[$preparedException->getStatusCode()]
                    ),
                    'status' => $preparedException->getStatusCode()
                ],
                $preparedException->getStatusCode(),
                $preparedException->getHeaders()
            );
        }
    
        return parent::render($request, $exception);
    }
    

    或者,如果您进一步查看渲染,覆盖 renderHttpException 可能会更安全一些。这将删除views/errors中的自定义错误页面

    protected function renderHttpException(HttpException $e)
    {
        return response(
            [
                'message' => sprintf(
                    '%d %s',
                    $e->getStatusCode(),
                    Response::$statusTexts[$e->getStatusCode()]
                ),
                'status' => $e->getStatusCode()
            ],
            $e->getStatusCode(),
            $e->getHeaders()
        );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-20
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-23
      相关资源
      最近更新 更多