2
votes

Earlier, when we started our project only with Cognito User Pool I created lot of resolvers with validation by Cognito User Pool data, for example:

#if( $ctx.identity.claims["custom:role"] == "admin" )
...some code...(get data, invoke lambda, e.t.c.)
#else
  $utils.unauthorized()
#end

But later we needed other authorization providers (Facebook, Google e.t.c.). Therefore, we migrated to cognitoIdentityId, but there was a problem obtaining user data from the Cognito User Pool in the AppSync resolvers. In AWS Lambda I found Cognito User Pool id by the cognitoIdentityAuthProvider and can get Cognito User Attributes as UserAttributes see code below:

...
...
const cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider({
  apiVersion: '2016-04-18',
});

const getCognitoUserPoolId = (authProvider) => {
  const parts = authProvider.split(':');
  return parts[parts.length - 1].slice(0, -1);
};

// cognitoIdentityAuthProvider, which we pass as an parameter($ctx.identity.cognitoIdentityAuthProvider) from the AppSync resolver
const SUB = getCognitoUserPoolId(cognitoIdentityAuthProvider);

const params = {
  UserPoolId: COGNITO_USER_POOL_ID,
  Username: SUB,
};

try {
  const { UserAttributes } = await cognitoidentityserviceprovider.adminGetUser(params).promise();
  ...
  ...
} catch (error) {
 return error;
}

The question is how to get data from Cognito User Pool using cognitoIdentityId in AppSync resolvers? Or are there any other options? Hope I do not have to create a separate lambda for each resolver?

1

1 Answers

5
votes

I assume you are using AWS_IAM as the authorization type on your GraphQL API and you are federating a cognito user pool user through Cognito Federated Identities to obtain temporary AWS credentials that you use to call your GraphQL API.

At the moment, the federating user information is not available in the $context.identity object. The workaround for this is what you posted to retrieve it using a lambda and use it further in your resolver by using pipeline resolvers for example.

I am on the AppSync team and we have heard this feature request in the past so I will +1 it for you on your behalf.