title: Restrict S3 Object Access to Specific Cognito Users
body: <p>I am working on an application that will manage access to purchased files that are stored in S3. I have files organized by product in S3, for example:</p>
  
  <pre><code>my-bucket
    ├── product-a
    │     ├── file-1
    │     ├── file-2
    │     └── file-3
    ├── product-b
    │     ├── file-1
    │     ├── file-2
    │     └── file-3
    └── etc...
  </code></pre>
  
  <p>I am also using Cognito to manage user identities and authentication. I would like to create an IAM role that all users will assume which will grant them access only to the files of products they have purchased. What would be the proper way to do this? I have read thru <a href="https://aws.amazon.com/documentation/cognito/" rel="noreferrer">Cognito's documentation</a> and I feel I am just not quite connecting the dots.</p>
  
  <p>I see from <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_examples.html#iam-policy-example-cognito" rel="noreferrer">this</a> example, that I could provide each user access to their own folder in a bucket, but then I would have to copy the files to each user's folder, which seems both inefficient and prone to error.</p>
  
  <pre><code>{
    "Version": "2012-10-17",
     "Statement": [
     {
       "Effect": "Allow",
       "Action": ["s3:ListBucket"],
       "Resource": ["arn:aws:s3:::my-bucket"],
        "Condition": {"StringLike": {"s3:prefix": ["cognito/myapp/"]}}
      },
      {
        "Effect": "Allow",
        "Action": [
          "s3:GetObject"
        ],
        "Resource": [
          "arn:aws:s3:::my-bucket/myapp/${cognito-identity.amazonaws.com:sub}",
          "arn:aws:s3:::my-bucket/myapp/${cognito-identity.amazonaws.com:sub}/*"
        ]
      }
    ]
  }
  </code></pre>
  
  <p>But I was hoping to create a policy that would grant a user access to the folder of <code>product-a</code> if and only if they had purchased that product, say using some flag that was contained in that user's Cognito Sync data.</p>
  
  <p>Is this possible? Am I just not using the correct tools? I think this must be a common use-case.</p>