Skip to content

Python调用STS临时授权访问OSS

 

 

 

from aliyunsdkcore import client
from aliyunsdksts.request.v20150401 import AssumeRoleRequest
import json
import oss2


endpoint = 'oss-cn-hangzhou.aliyuncs.com'
# 用户key id
access_key_id = ''
# 用户key secret
access_key_secret = ''
# oss bucket名称
bucket_name = 'test'
object_name = ''
# role_arn为角色的资源名称。
role_arn = 'acs:ram::116140119:role/test'

# 创建policy_text。
# 仅允许对名称为test-bucket1的Bucket下的所有资源执行GetObject操作。  设置权限策略以进一步限制STS Token获取的权限
policy_text = '{"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}'

clt = client.AcsClient(access_key_id, access_key_secret, 'cn-hangzhou')
req = AssumeRoleRequest.AssumeRoleRequest()

# 设置返回值格式为JSON。
req.set_accept_format('json')
req.set_RoleArn(role_arn)
#设置会话名称,审计服务使用此名称区分调用者
req.set_RoleSessionName('test')
req.set_Policy(policy_text)
#发起请求,并得到响应
body = clt.do_action_with_exception(req)

print(body)

# 使用RAM账号的AccessKeyId和AccessKeySecret向STS申请临时token。
token = json.loads(oss2.to_unicode(body))

# 使用临时token中的认证信息初始化StsAuth实例。
auth = oss2.StsAuth(token['Credentials']['AccessKeyId'],
                    token['Credentials']['AccessKeySecret'],
                    token['Credentials']['SecurityToken'])

# 使用StsAuth实例初始化存储空间。
bucket = oss2.Bucket(auth, endpoint, bucket_name)

print(bucket.sign_url('GET', 'settlement_excel_download/20200812200526.png', 60))

 

STS中临时授权时出现“You are not authorized to do this action. You should be authorized by RAM“报错

代码中使用的AccessKey和AccessKeySecret是主账号的,并非RAM用户的。 必须要创建子帐号才key才可以

 

 

https://help.aliyun.com/document_detail/100624.html?spm=a2c4g.11186623.2.10.5e474529lXELjN#concept-xzh-nzk-2gb

https://help.aliyun.com/document_detail/28798.html?spm=a2c4g.11186623.2.10.29bc203dUpOWmQ#reference-smb-tzy-xdb

https://help.aliyun.com/document_detail/32033.html?spm=a2c4g.11186623.2.23.64e33b49Q6fLpK#section-zx1-55k-kfc

Be First to Comment

发表评论

电子邮件地址不会被公开。 必填项已用*标注