Limiting Resolver Permissions by Cognito Group

Tags: appsync dynamodb cognito velocity vtl

With AWS AppSync used in conjunction with Cognito and DynamoDB, you can implement permissions that use Cognito groups to determine access.

Read Permissions for Owner or Admin Only

Suppose you have a list of items belonging to different users, and you want:

  • Non-admin users to only see their own items
  • Admin users to see all items

Here's a request mapping template where the filter condition is only added if you are not in the admin Cognito group:

{
  "version": "2017-02-28",
  "operation": "Scan",
  #if (!$ctx.identity.claims["cognito:groups"].contains("admin"))
  "filter" : {
    "expression": "customer.username = :username",
    "expressionValues" : {
      ":username" : {
        "S": "${ctx.identity.username}"
      }
    }
  },
  #end
  "limit": $util.defaultIfNull($ctx.args.limit, 20),
  "nextToken": $util.toJson($util.defaultIfNullOrEmpty($ctx.args.nextToken, null)),
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

This performs a Scan operation on your DynamoDB table, filtering on the customer's username only if you are not an admin.

The corresponding response mapping template needs no modification, since filtering is done in the request:

$util.toJson($context.result)
1

Delete Permissions for Admin Only

Suppose you only want Cognito users in the admin group to be able to delete items. Here's a request mapping template that implements that:

#if ($ctx.identity.claims["cognito:groups"].contains("admin"))
{
    "version" : "2017-02-28",
    "operation" : "DeleteItem",
    "key" : {
        "id" : $util.dynamodb.toDynamoDBJson($ctx.args.id)
    }
}
#else
$util.unauthorized()
#end
1
2
3
4
5
6
7
8
9
10
11

If you are authenticated as a Cognito user who isn't an admin, when you go to a page that attempts to execute a delete mutation, the response will be errorType: Unauthorized.


Copyright © 2018 Daniel and Audrey Roy Greenfeld.
Site Map

Last Updated: 9/1/2018, 10:30:42 PM