How to Limit REST API to User-Specific Content

2020-04-19 15:07发布

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

2条回答
Ridiculous、
2楼-- · 2020-04-19 15:18

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.

查看更多
戒情不戒烟
3楼-- · 2020-04-19 15:22

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!

查看更多
登录 后发表回答