【问题标题】:Restricting update on API endpoint for unauthorized users限制未经授权的用户对 API 端点的更新
【发布时间】:2019-02-22 20:34:22
【问题描述】:

我已经使用 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 状态代码。

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

【问题讨论】:

  • 发现错误,我没有返回错误响应。

标签: php laravel laravel-5.6


【解决方案1】:

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

【讨论】:

  • 我想通了。谢谢大佬
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-01
相关资源
最近更新 更多