AWS Amazon S3 存储桶设置开放外部访问
aws s3存储桶中的资源要开放访问,需要开放公共访问权限,配置存储桶策略,否则访问失败,失败提示内容示例如下:
1
2
3
4
5
6
7
|
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>AAC80Y53HNV9K6CF</RequestId>
<HostId>KJH8wu7aOGbcB8eV2tw++FLH0RLDD2i3kyPYaOW8E4uaTAntexKIzidkFKikEvfpp2pj3OPGWMbkIkh7XTwFAg==</HostId>
</Error>
|
设置存储桶公共访问权限
- 打开存储桶权限,然后编辑 屏蔽公共访问权限(存储桶设置)
- 开放公共访问权限后,编辑 存储桶策略
打开 AWS Policy Generator , 在界面上设置并生成json格式策略。
ARN按下面格式配置,用当前存储桶名称
生成存储桶策略json示例如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
{
"Version": "2012-10-17",
"Id": "Policy1825033712922",
"Statement": [
{
"Sid": "Stmt1725023806069",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::<BucketName>/<KeyName>"
}
]
}
|
配置生效后,刷新即可正常访问资源。
s3文件上传
使用python sdk上传文件 Quickstart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import boto3
# Let's use Amazon S3
s3 = boto3.resource(
's3',
aws_access_key_id="XXXX", # accesskey、secretkey、sessiontoken
aws_secret_access_key="secretkey",
aws_session_token="sessionToken",
region_name="region_name"
)
# Upload a new file
data = open('test.jpg', 'rb')
s3.Bucket('my-bucket').put_object(Key='test.jpg', Body=data)
|
Boto3 Configuration
Restrict access to a specific HTTP referer
s3存储桶防盗链策略配置示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
{
"Version":"2012-10-17",
"Id":"HTTP referer policy example",
"Statement":[
{
"Sid":"Allow only GET requests originating from www.example.com and example.com.",
"Effect":"Allow",
"Principal":"*",
"Action":["s3:GetObject","s3:GetObjectVersion"],
"Resource":"arn:aws:s3:::amzn-s3-demo-bucket/*",
"Condition":{
"StringLike":{
"aws:Referer":[
"http://www.example.com/*",
"http://example.com/*"
]
}
}
}
]
}
|
参考