How to Limit REST API to User-Specific Content

删除回忆录丶 提交于 2019-12-20 04:16:14

问题


I have a fairly simple API setup on a MEAN stack using PassportJS. I have no problems setting up my routes with no security (grabbing general data) and with user authentication (secure information). However, I cannot seem to find a best practices for granted user-based access.

For example: /api/users/:id is a route that requires authentication. So you can never get user information without an access token.

However, once I have a token, I can simply send that with a request and someone ELSE's id to access their content instead of their own. Albeit, the id's are long messy things, if someone where to get a person's ID from the system, they only need their own password to access that data.

I considered saving the token in a new collection called sessions and doing additional verification to match the token/userId combo. But I don't know if that's the best practice.

Does Passport handle that auto-magically and I missed that part?

Thanks, Wayne


回答1:


You already have authentication put in place, so what you now need to implement is authorization.

Authentication: Validating an identity as true or false—generally used to verify that a user is who he/she says they are. Most commonly achieved through a username/password combination, but the same principle applies to other forms of authentication like secret questions, secret links, bio-metric identification, etc.

Authorization Specifying which resources a user (with a given identity) should be allowed to access.

(source: Auth0 Identity Glossary)

If your authentication system is designed correctly the access token presented in order to be granted initial access to /api/users/:id endpoint will allow you to know which user is calling your application so now what you need to do is implement the business rules that dictate which data can the user access on each individual endpoint.

For the /api/users/:id case, if you want users to only be allowed to access their own data, the rule might be as simple as checking that the user identifier requested on the API route matches the user identifier associated with the access token. Given that the access token needs to be implemented in such way that it cannot be tampered, you guarantee that only the correct user is granted access to the data.




回答2:


It seems that you are missing an api check on the userId

for e.g. you have a route like /api/:userId/data/:dataId and you would like to ensure that only users who are allowed to access this data item can do so. Then what you would need to do is check that the userId provided in your authentication token is the same as the userId in the api route!



来源:https://stackoverflow.com/questions/39965304/how-to-limit-rest-api-to-user-specific-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!