As per AWS documentation, you can use two different Cognito groups to access same AppSync API accessing the same DynamoDB table by following ways, which are pretty straight forward;
If you use aws_auth
directive
type Query {
getPosts:[Post!]!
@aws_auth(cognito_groups: ["Bloggers", "Readers"])
}
If you use aws_cognito_user_pools
directive
type Query {
getPosts:[Post!]!
@aws_api_key @aws_cognito_user_pools(cognito_groups: ["Bloggers", "Readers"])
}
Now, if you specifically want two different user pools for your same API and DynamoDB table, then you will have to go little extra mile to achieve this. Following are the steps:
- Add both of your user pools as Additional authorization
providers in your AppSync settings.
- Use
@aws_cognito_user_pools
directive with your queries and
mutation in the schema and the object these queries and mutations are trying to access.
- This is a tricky one! When you try to access the
$ctx.identity.cognitoIdentityPoolId
in your query/mutation resolver, it will throw you null. Because cognitoIdentityPoolId
is only included in AWS_IAM
authorization header and not in AWS_COGNITO_USER_POOLS
[Ref.]. However, you can still get user pool ID from iss
field in $ctx.identity.claims
and it will look something like https://cognito-idp.us-xxxx-x.amazonaws.com/us-xxxx-X_XxxXxxXX
. This us-xxxx-X_XxxXxxXX
is your user pool ID which you will have to parse somehow.
- After parsing user pool ID, you can filter your users based on
Cognito pool ID and then granting them the access to the table you
desire.