'How can I connect users in Cognito with their data in DynamoDB?
I'm trying to implement a solution in my Vue.js web app whereby users are authenticated via AWS Cognito. I'm using DynamoDB as the backend database. What I'm trying to achieve is to connect the authenticated users with their corresponding table/collection (and only their corresponding resource) in DynamoDB. So basically, once the user is signed in, they see their own db table in their account.
As far as my research goes, this would be a utilization of the IAM policy, whereby each user is authorized to access a certain resource on DynamoDB.
What I've done so far:
1-Created a user pool
2- Created an identity pool
3- Connected both user and identity pools.
4- Can now sign up and sign in users. The user is assigned a token once they login.
So my main question here is how do I use this token to scan/query a table for that user only ?
The best approach I could think of is to use the specific Cognito user ID as their table name in DDB. Then in the app, once the user is authenticated, if their user ID match with their DDB table name they can read the table.
What would be the best approach to do this ?
Solution 1:[1]
For those looking for an answer, there are multiple ways you can accomplish what's called fine grained access control with DynamoDB:
- As also mentioned by @hephalump, you can create an IAM policy that basically uses the Cognito identity id ( different from that of Cognito id or sub ) of the user as the hash key in the DynamoDB table. The policy checks to see if the Cognito identity id of the requester matches that of the hash key of the record they are trying to access. If it does, they will be given access to the record, if not, they will be denied access. Read more.
- Another way is to create an AppSync API and use the owner field to restrict access based on the logged in user. Along with enabling fine grained access control, you will have the advantage of having a GraphQL API. More here and here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ninsonTan |