简体   繁体   English

REST API设计-获取所有用户,如何处理私人信息?

[英]REST API design - GET all users, how to handle private info?

I'm working on a REST API and getting a little lost in my head. 我正在使用REST API,但有点不知所措。 I have a Model for Users, and I'm storing the (salted) passwords in a database. 我有一个“用户模型”,并将(加盐的)密码存储在数据库中。

Consider a consumer of the API: I would want them to be able to get all other users public info (GET /users, /users/:id) but I would want the passwords to be left out. 考虑一下API的使用者:我希望他们能够使所有其他用户获得公共信息(GET / users,/ users /:id),但是我希望密码被忽略。

However if for example I wanted to update info of the logged in user in a regular PUT request, then I wouldn't have the user's existing password to send in the PUT request - so a PUT request would only do a partial update of the user on all it's other fields. 但是,例如,如果我想在常规的PUT请求中更新已登录用户的信息,那么我将没有用户的现有密码可发送到PUT请求中-因此,PUT请求只会对用户进行部分更新在所有其他领域。 This doesn't seem very RESTful. 这似乎不是很RESTful的。 (Maybe I should use PATCH? It seems patch isn't widely used. Is there a reason for this?) (也许我应该使用PATCH?似乎patch没有得到广泛使用。是否有原因?)

Right now I'm thinking of having a POST at /users/:id/updatePassword to update passwords and then a PUT at /users/:id to update everything else about the user EXCEPT the password, and no way to retrieve a users password from the API. 现在,我正在考虑POST at /users/:id/updatePassword进行POST at /users/:id/updatePassword来更新密码,然后PUT at /users/:id进行PUT at /users/:id来更新有关用户的所有其他信息(除了密码之外),并且无法检索用户密码从API。

However to me this feels .... strange. 但是对我来说,这感觉很奇怪。 Maybe it's not, but just wondering if anyone has any better ideas how to design this? 也许不是,但是只是想知道是否有人对如何设计这个有更好的想法?

Thanks 谢谢

First of all, you should not stored your users password encrypted. 首先,您不应将用户密码加密存储。 You should salt and hash them and store the hash of the salted password. 您应该对它们加盐并对其进行哈希处理,并存储盐化密码的哈希值。

The database model of your user does not have to match the resource you expose in your REST API to the user. 用户的数据库模型不必与您在REST API中向用户公开的资源相匹配。 When you use PUT to update the user, you should expect all fields in the resource as PUT is idempotent. 当使用PUT更新用户时,由于PUT是幂等的,因此应该期望资源中的所有字段。

The way you propose to update the password (using POST /users/:id/updatePassword is perfectly fine and RESTful. In your database model, you can combine the password hash with the other fields of the user, but in your resource, you keep them separate. 您建议的更新密码的方式(使用POST /users/:id/updatePassword完全正确且具有RESTful功能。在数据库模型中,您可以将密码哈希与用户的其他字段结合使用,但是在您的资源中,您可以保留他们分开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM