Amazon S3 Bucket策略,只允许一个域访问文件

时间:2015-07-28 14:57:20

标签: amazon-web-services amazon-s3 same-origin-policy

我有一个带有文件的S3存储桶。我只希望某个域能够访问该文件。我已经尝试了一些关于存储桶的策略,但都没有工作,这个是来自AWS documentation

{
    "Version": "2012-10-17",
    "Id": "http referer policy example",
    "Statement": [
        {
            "Sid": "Allow get requests originated from www.example.com and example.com",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::my-bucket-name/*",
            "Condition": {
                "StringLike": {
                    "aws:Referer": [
                        "http://www.phpfiddle.org/*",
                        "http://phpfiddle.org/*"
                    ]
                }
            }
        }
    ]
}

为了测试文件,我在phpfiddle.org上托管了一段代码并拥有此代码。但我无法通过浏览器或phpfiddle代码直接访问此文件。

<?php 
    $myfile = file_get_contents("https://s3-us-west-2.amazonaws.com/my-bucket-name/some-file.txt");
    echo $myfile;
    ?>

以下是文件的权限,存储桶本身也具有相同的权限+上述策略。

enter image description here

这只是一个示例链接,而不是实际工作的链接。

1 个答案:

答案 0 :(得分:3)

The Restricting Access to a Specific HTTP Referrer bucket policy is only allow your file to be accessed from a page from your domain (the HTTP referrer is your domain).

Suppose you have a website with domain name (www.example.com or example.com) with links to photos and videos stored in your S3 bucket, examplebucket.

You can't direct access your file from your browser (type directly the file URL into browser). You need to create a link/image/video tag from any page in your domain.

If you want to file_get_contents from S3, you need to create a new policy to allow your server IP (see example). Change the IP address to your server IP.

Another solutions is use AWS SDK for PHP to download the file into your local. You can also generate a pre-signed URL to allow your customer download from S3 directly for a limited time only.

相关问题