安全凭证服务(STS)
STS即Secure Token Service 是一种安全凭证服务,可以使用STS来完成对于临时用户的访问授权。对于跨用户短期访问s3资源时,可以使用STS服务。这样就不需要透露主账号AK/SK,只需要生成一个短期访问凭证给需要的用户使用即可,避免主账号AK/SK泄露带来的安全风险。
access_key = '<your-access-key>'
secret_key = '<your-secret-access-key>'
end_point = '<your-endpoint>'
region = 'cn'
self.sts_client = boto3.client(
'sts',
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
endpoint_url=end_point,
region_name=region)
def assume_role(self):
print('assume_role')
bucket = '<your-bucket>'
policy = r'{"Version":"2012-10-17","Statement":{"Effect":"Allow","Action":["s3:*"]' \
r',"Resource":["arn:aws:s3:::%s","arn:aws:s3:::%s/*"]}}' % (bucket, bucket)
role_arn = "arn:aws:iam:::role/<your-role>"
role_session_name = "<your-session-name>"
print('policy: %s' % policy)
response = self.sts_client.assume_role(
Policy=policy,
RoleArn=role_arn,
RoleSessionName=role_session_name,
)
print('ak %s' % response['Credentials']['AccessKeyId'])
print('sk %s' % response['Credentials']['SecretAccessKey'])
print('token %s' % response['Credentials']['SessionToken'])
允许所有的操作
{"Version":"2012-10-17","Statement":{"Effect":"Allow","Action":["s3:*"],"Resource":["arn:aws:s3:::<your-bucket-name>","arn:aws:s3:::<your-bucket-name>/*"]}}
限制只能上传和下载
{"Version":"2012-10-17","Statement":{"Effect":"Allow","Action":["s3:PutObject","s3:GetObject"],"Resource":["arn:aws:s3:::<your-bucket-name>","arn:aws:s3:::<your-bucket-name>/*"]}}
使用分片上传
{"Version":"2012-10-17","Statement":{"Effect":"Allow","Action":["s3:PutObject","s3:AbortMultipartUpload","s3:ListBucketMultipartUploads","s3:ListMultipartUploadParts"],"Resource":["arn:aws:s3:::<your-bucket-name>","arn:aws:s3:::<your-bucket-name>/*"]}}
其他操作权限
上传权限:s3:PutObject
下载权限:s3:GetObject
删除权限:s3:DeleteObject
获取列表权限:s3:ListBucket
注意:
1.ListObjects 操作是由ListBucket权限控制的
2."Version:2012-10-17"是系统的policy格式的版本号,不能改成其他日期
更多操作权限可以参考:
https://awspolicygen.s3.amazonaws.com/policygen.html
参数 | 类型 | 描述 |
---|---|---|
RoleArn | String | 角色的ARN,在控制台创建角色后可以查看 |
Policy | String | 角色的policy,需要是json格式,限制长度1~2048 |
RoleSessionName | String | 角色会话名称,此字段为用户自定义,限制长度2~64 |
DurationSeconds | Integer | 会话有效期时间,默认为3600s,范围15分钟至12小时 |