【问题标题】:How to secure Spring Data REST associations requests?如何保护 Spring Data REST 关联请求?
【发布时间】:2019-08-14 23:05:48
【问题描述】:

我使用 Spring Data REST 创建了 REST API。我有实体UserPost,其中User 可以有多个帖子(一对多)。现在我需要向我的用户添加帖子。但我需要userA 不能删除或更新userB 的帖子。

API 结构

{
    "_links": {
        "users": {
            "href": "http://localhost:8081/api/users{?page,size,sort}",
            "templated": true
        },
        "posts": {
            "href": "http://localhost:8081/api/posts{?page,size,sort}",
            "templated": true
        }
        "profile": {
            "href": "http://localhost:8081/api/profile"
        }
    }
}

用户结构

{
    "id": 1,
    "username": null,
    "password": null,
    "_links": {
        "self": {
            "href": "http://localhost:8081/api/users/1"
        },
        "user": {
            "href": "http://localhost:8081/api/users/1"
        },
        "posts": {
            "href": "http://localhost:8081/api/users/1/posts"
        }
    }
}

有几种方法可以添加相关的实体抛出链接。 使用PUT 方法和text/uri-list 内容类型:

PUT /api/posts/1/user? HTTP/1.1
Host: localhost:8081
Content-Type: text/uri-list
Authorization: Bearer 270c6dc3-04a5-48cc-b42e-c275472df459
cache-control: no-cache
http://localhost:8081/api/users/1

但是通过这种方式,我可以将任何 URI 添加到正文并将任何随机用户添加到随机帖子,我认为这里存在安全问题。 添加相关资源的下一个方法是将其添加到 JSON 中,如下所示:

PATCH /api/posts/1? HTTP/1.1
Host: localhost:8081
Content-Type: application/json
Authorization: Bearer 270c6dc3-04a5-48cc-b42e-c275472df459
cache-control: no-cache
{
    "user": "http://localhost:8081/api/users/1"
}

但是和在这个方法中同样的问题。任何用户都可以添加到任何帖子中。

现在我只看到这个问题的一个解决方案 - 自定义 rest 存储库并检查添加的用户是否是当前经过身份验证的用户。

【问题讨论】:

    标签: java spring spring-security spring-data-rest


    【解决方案1】:

    查看您的用例“只有用户负责其 POST 上的 CRUD 操作”

    是的,解决此问题的一种方法是“自定义 rest 存储库并检查添加的用户是否是当前经过身份验证的用户。”

    假设你有 Spring Security

    我建议您不要为您的帖子传递任何用户 ID,并从安全上下文或令牌中的登录用户 ID 中获取用户。

    这样您的帖子将在 API 级别独立于用户。

    【讨论】:

      猜你喜欢
      • 2020-05-29
      • 2019-12-25
      • 2020-12-03
      • 2018-10-08
      • 2019-06-19
      • 2019-07-23
      • 2018-03-27
      • 2019-12-12
      • 2014-04-23
      相关资源
      最近更新 更多