Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cognito custom claims missing with Amplify but not with Appsync Console

I have the following resolver, allowing me to retrieve information about the current user company (companyId is added as a custom field on the cognito user pool). The field on cognito is set to mutable.

{ "version" : "2017-02-28", "operation" : "GetItem", "key": { "id" : $util.dynamodb.toDynamoDBJson($context.identity.claims.get("custom:companyId")) } }

-

This works fine when using the AWS AppSync interface (after login in) as the logs show:

{ "errors": [], "mappingTemplateType": "Request Mapping", "path": "[getMyClientCompany]", "resolverArn": "arn:aws:appsync:eu-west-1:261378271140:apis/rue25cac6jc6vfbhvu32sjafqy/types/Query/fields/getMyClientCompany", "transformedTemplate": "{\n \"version\" : \"2017-02-28\",\n \"operation\" : \"GetItem\",\n \"key\": {\n \"id\" : {\"S\":\"0c1c81db-a771-4856-9a30-d11bf8e3cab1\"}\n }\n}", "context": { "arguments": {}, "source": null, "result": null, "error": null, "outErrors": [] }, "fieldInError": false }

-

But doesn't work when the code comes from Amplify-js:

{ "errors": [], "mappingTemplateType": "Request Mapping", "path": "[getMyClientCompany]", "resolverArn": "arn:aws:appsync:eu-west-1:261378271140:apis/rue25cac6jc6vfbhvu32sjafqy/types/Query/fields/getMyClientCompany", "transformedTemplate": "{\n \"version\" : \"2017-02-28\",\n \"operation\" : \"GetItem\",\n \"key\": {\n \"id\" : {\"NULL\":null}\n }\n}", "context": { "arguments": {}, "source": null, "result": null, "error": null, "outErrors": [] }, "fieldInError": false }

The key that should be "custom:companyId" is "NULL" now I imagine the issue is either with Amplify (version 0.4.8) or with the cognito user resolver for some reason

Any idea what could be going on?

like image 635
lepthy Avatar asked Aug 14 '18 12:08

lepthy


1 Answers

There are two JWT tokens Cognito may utilize. ID and Access. ID token seems to contain those custom claims.

From Amplify you tweak the Authorization header to use ID token vs Access token.

Here's the code, put it in AWS Amplify configuration:

API: {
  graphql_endpoint: 'https://****.appsync-api.***.amazonaws.com/graphql',
  graphql_region: '***',
  graphql_authenticationType: 'AMAZON_COGNITO_USER_POOLS',
  graphql_headers: async () => {
    try {
      const token = (await Auth.currentSession()).idToken.jwtToken;
      return { Authorization: token }
    }
    catch (e) {
      console.error(e);
      return {};
      // Potentially you can retrieve it from local storage
    }
  }
}

Note, there seem to be several different keys to configure Amplify keys: for example, aws_appsync_graphqlEndpoint vs API { graphql_endpoint }, I used the latter.

like image 173
Mark Sergienko Avatar answered Oct 06 '22 20:10

Mark Sergienko