简体   繁体   中英

Cognito Role and AWS S3 Bucket policy for mobile and web access

Our goal is to create S3 bucket and IAM role policies that will only allow S3 access to our logged in users.

We are hosting private files on an S3 bucket that will be accessed from both a web and mobile app. We are attempting to add a layer of security with Amazon Cognito, using an unauthenticated role, so that any users signed into our application can access the S3 bucket.

Using the AWS-SDK for JS and following the basic AWS.config.credentials setup, we can see 1 identity accessed and the number of syncs in our Amazon Cognito Identity Dashboard. Since we seem to be connecting to the IdentityPool, I'm thinking that our policies may need some tweaking so that logged in users that have the unauthenticated Cognito role can access the S3 bucket.

IAM Role policy for Cognito_IdentityPoolUnauth_Role

{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "SID_NUMBER",
        "Effect": "Allow",
        "Action": [
            "s3:*"
        ],
        "Resource": [
            "arn:aws:s3:::OUR_BUCKET_NAME/*"
        ]
    }
  ]
}

S3 BUCKET POLICY

{
"Version": "2012-10-17",
"Id": "http referer policy example",
"Statement": [
    {
        "Sid": "",
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::IAM_NUMBER:role/Cognito_IdentityPoolUnauth_Role"
        },
        "Action": "s3:*",
        "Resource": "arn:aws:s3:::OUR_BUCKET_NAME/*"
    }
  ]
}

When you attempt to access the files directly from the browser, no credentials are sent with the request. It has the same effect as trying to hit S3 directly without having any code to get credentials from Cognito. In order to use the Cognito credentials, you need to make the request using the javascript SDK. Below is a example request using the javascript SDK taken from this page

var s3 = new AWS.S3();
var params = {Bucket: 'myBucket', Key: 'myKey'};
s3.getSignedUrl('getObject', params, function (err, url) {
  console.log("The URL is", url);
});

If you call this after getting Cognito credentials, it will use Cognito credentials to create a signed url to access the key myKey in bucket myBucket. You can take an approach similar to this to listObjects in your bucket and then generate signed urls (signed with Cognito credentials) that your end users can click on to view the contents of each key in your bucket.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM