Search code examples
amazon-dynamodbamazon-cognitoaws-appsyncaws-amplifyvtl

Simple GetItem with ctx.identity.username returns null


I'm using AppSync with IAM auth with a DynamoDB resolver and Cognito. I'm trying to do the following.

{
    "version": "2017-02-28",
    "operation": "GetItem",
    "key": {
        "userId": $util.dynamodb.toDynamoDBJson($ctx.identity.username)
    }
}

$ctx.identity.username is supposed to contain userId generated by Cognito and I'm trying to use it to fetch current user data.

Client side, I'm using AWS Amplify that tells me I'm currently logged:

this.amplifyService.authStateChange$.subscribe(authState => {
  if (authState.state === 'signedIn') {
    this.getUserLogged().toPromise();
    this._isAuthenticated.next(true);
  }
});

getUserLogged is the Apollo query that is supposed to returns user data.

What I've tried:

  • If I leave it like this, getUserLogged returns null.
  • If I replace in the resolver $util.dynamodb.toDynamoDBJson($ctx.identity.username) with a known userId like this $util.dynamodb.toDynamoDBJson("b1ad0902-2b70-4abd-9acf-e85b62d06fa8"): It works! I get this user data.
  • I tried to use the test tool in the resolver page but it only gives fake data so I can't rely on this.

Did I make a mistake? To me everything looks good but I guess I'm missing something?

Can I clearly see what $ctx.identity contains?


Solution

  • You'll want to use $ctx.identity.cognitoIdentityId to identify Cognito IAM users: https://docs.aws.amazon.com/appsync/latest/devguide/resolver-context-reference.html#aws-appsync-resolver-context-reference-identity

    You could see the contents of $ctx.identity by creating a Lambda resolver and logging the event or by creating a local resolver and returning the input that the mapping template receives: https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-local-resolvers.html

    My cognitoIdentityId looks like this: eu-west-1:27ca1e79-a238-4085-9099-9f1570cd5fcf