Search code examples
amazon-web-servicesamazon-dynamodbaws-appsync

Fine Grained Access to a single Item - GetItem, DynamoDB Resolver AppSync


How do I provide Fine Grained Access to a Single item in AppSync. I have the following resolver for the GetItem operation.

{   
    "version": "2017-02-28",
    "operation": "GetItem",
    "key": {
       "identityId": $util.dynamodb.toDynamoDBJson($ctx.args.identityId),
       "id": $util.dynamodb.toDynamoDBJson($ctx.args.id),   
    },   
    "condition": {
       "expression": "attribute_exists(#author) AND #author = :author",
       "expressionNames": {
          "#identityId": "identityId",
          "#id": "id",
          "#author": "author"
       },
       "expressionValues": {
          ":author" : { "S" : "${ctx.identity.cognitoIdentityId}" }
       }   
    }
}

However when I run the query I got:

GraphQL error: Unsupported element '$[condition]'.

Which is ok, because according to the documentation there is not condition key for this operation https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-dynamodb.html#aws-appsync-resolver-mapping-template-reference-dynamodb-getitem

My Question How can I filter/restrict access to items belonging to the particular author (Fine grained access) if I cannot put conditions?


Solution

  • You can filter your result in the response mapping template such as below. From my understanding, you are getting the author field from the cognitoIdentityId and your item has a different primary key hence why you can't use the author when querying.

    #if($context.result["author"] == $ctx.identity.cognitoIdentityId)
        $utils.toJson($context.result);
    #else
        $utils.unauthorized()
    #end