首页 > 解决方案 > How to secure Spring Data REST associations requests?

问题描述

I'v created REST API using Spring Data REST. I have entity User and Post, where User can have multiple posts (One to Many). Now I need to add posts to my user. But I need that userA can't have possibilities to delete or update posts of userB.

Api structure

{
    "_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"
        }
    }
}

User structure

{
    "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"
        }
    }
}

There are several ways to add related entity throw links. Using PUT method and text/uri-list content type:

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

But with this way I can add any URI to body and add any random user to random post, and I think, there is a security problem here. Next method to add related resource is to add it in JSON like this:

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"
}

But and in this method the same problem. Any user can be added to any post.

Now I see only one solve of this problem - is customizing rest repository and check if added user is current authenticated user.

标签: javaspringspring-securityspring-data-rest

解决方案


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

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

假设你有 Spring Security

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

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


推荐阅读