[英]How to secure Spring Data REST associations requests?
我使用 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"
}
但是和在这个方法中同样的问题。 任何用户都可以添加到任何帖子。
现在我只看到这个问题的一个解决方案 - 自定义其余存储库并检查添加的用户是否是当前经过身份验证的用户。
查看您的用例“只有用户负责其 POST 上的 CRUD 操作”
是的,解决此问题的一种方法是“自定义其余存储库并检查添加的用户是否是当前经过身份验证的用户”。
假设你有 Spring Security
我建议您不要为您的帖子传递任何用户 ID,并从安全上下文或令牌的登录用户 ID 中选择用户。
这样您的帖子将在 API 级别独立于用户。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.