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

Restricting update on API endpoint for unauthorized users

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

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

使用 postman,除了更新和删除操作外,该应用程序按预期工作。如果用户试图更新一本不属于他们的书,我希望返回一个错误响应。不幸的是,我得到了 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);
    }
}

注意:在邮递员中测试时,我只是在 headers 授权字段中添加不记名令牌。当用户拥有这本书时有效,但当这本书不属于登录用户时,状态代码是 200 而不是 403。

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

您似乎没有 return 您在 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