限制未经授权用户的API端点更新

问题描述 投票:0回答:1

我已经使用API​​资源构建了一个仅API应用程序,并使用Passport进行身份验证。该应用程序执行以下操作

  1. 允许每个人列出所有书籍并查看特定书籍
  2. 仅允许登录用户添加,更新和删除属于他们的书籍

使用邮递员,应用程序按预期工作,但更新和删除操作除外。如果用户尝试更新不属于他们的书,我想要返回错误响应。不幸的是,我获得了200 Ok状态代码而不是我的自定义消息和403状态代码。删除也是一样的。

这是我的BookController更新和删除方法

public function update(Request $request, Book $book)
{
    // Update book if the logged in user_id is the same as the book user_id
    if ($request->user()->id === $book->user_id) {
        $book->update($request->only(['title', 'author']));

        return new BookResource($book);
    } else {
        response()->json(['error' => 'You do not have the permission for this operation'], 403);
    }
}

public function destroy(Request $request, Book $book)
{
    // Delete book only if user_id matches book's user_id
    if ($request->user()->id === $book->user_id) {
        $book->delete();

        return response()->json(null, 204);
    } else {
        response()->json(['error' => 'You do not have the permission for this operation'], 403);
    }
}

注意:在邮递员中进行测试时,我只需在标题授权字段中添加承载标记即可。当用户拥有该书但当该书不归登录用户所有时获得200而不是403状态代码时起作用。

我做错了什么,我该如何解决?

php laravel laravel-5.6
1个回答
2
投票

您似乎没有在else语句中返回您的响应 - 您可以像这样简化它:

public function update(Request $request, Book $book)
{
    // Update book if the logged in user_id is the same as the book user_id
    if ($request->user()->id === $book->user_id) {
        $book->update($request->only(['title', 'author']));

        return new BookResource($book);
    }

    return response()->json([
        'error' => 'You do not have the permission for this operation'
    ], 403);
}

public function destroy(Request $request, Book $book)
{
    // Delete book only if user_id matches book's user_id
    if ($request->user()->id === $book->user_id) {
        $book->delete();

        return response()->json(null, 204);
    }

    return response()->json(['error' => 'You do not have the permission for this operation'], 403);
}

我还建议可能会研究政策 - 并将它们作为中间件应用到路线https://laravel.com/docs/5.7/authorization#writing-policies

© www.soinside.com 2019 - 2024. All rights reserved.