okan Acer
okan Acer

Reputation: 61

Aws Amplify Using Multiple Cognito User Pools in One GraphQL Api

I am new in AWS Amplify and I am try to make simple project.

I have two different frontend(react) projects. One of them for blog readers and one of them for editors.For both applications, I want to use same DynamoDB tables(and use graphql api). But I want to use different user pools for each project. How can I implement this?

I was reading this article - https://medium.com/@fullstackpho/aws-amplify-multi-auth-graphql-public-read-and-authenticated-create-update-delete-1bf5443b0ad1

I know AWS AppSync supports multiple authorization types like cognito, api key ... But does it support two cognito type?

Thanks,

Upvotes: 0

Views: 4080

Answers (1)

Myz
Myz

Reputation: 828

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:

  1. Add both of your user pools as Additional authorization providers in your AppSync settings.
  2. 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.
  3. 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.
  4. 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.

Upvotes: 2

Related Questions