限制未经授权的用户在API终结点上的更新

时间:2018-09-18 18:43:02

标签: php laravel laravel-5.6

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

  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状态代码。

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

1 个答案:

答案 0 :(得分: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