我使用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
但是通过这种方式我可以向body添加任何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存储库并检查添加的用户是否是当前经过身份验证的用户。
查看您的用例“只有用户负责其POST上的CRUD操作”
是的一种解决方法是“自定义休息库并检查添加的用户是否是当前经过身份验证的用户”。
假设你有Spring Security
我建议您不要为您的帖子传递任何用户ID,并从安全上下文或令牌中登录用户ID中选择用户。
这样,您的帖子将独立于API级别的用户。