【发布时间】:2019-08-14 23:05:48
【问题描述】:
我使用 Spring Data REST 创建了 REST API。我有实体User 和Post,其中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