Can I specify an AWS DynamoDB policy based on Cognito ID?

Scott McKenzie picture Scott McKenzie · Sep 16, 2014 · Viewed 7k times · Source

Can I apply a policy to an AWS DynamoDB table but restrict it based on the Cognito ID of the user accessing it?

E.g. A Customer table has a primary hash key equal to the Cognito ID. When anyone but the user sharing the same ID tries to get the item they will receive an unauthorised exception.

(Non DynanoDB policies are probably also valid.)

Answer

Wolfwyrd picture Wolfwyrd · Sep 17, 2014

You should be able to do something like this using the same techniques as those for using an ID Provider. You should use the Cognito identifier as the key in the policy:

{
  "Version": "2012-10-17",
  "Statement": [{
      "Effect": "Allow",
      "Action": [
        "dynamodb:DeleteItem",
        "dynamodb:GetItem",
        "dynamodb:PutItem",
        "dynamodb:Query"
      ],
      "Resource": ["arn:aws:dynamodb:REGION:123456789012:table/UserData"],
      "Condition": {
        "ForAllValues:StringEquals": {
          "dynamodb:LeadingKeys": ["${cognito-identity.amazonaws.com:sub}"]}
    }
  }]
}