示例#1
0
    def fetch_sts_token(access_key_id, access_key_secret, role_arn):
        """子用户角色扮演获取临时用户的密钥
        :param access_key_id: 子用户的 access key id
        :param access_key_secret: 子用户的 access key secret
        :param role_arn: STS角色的Arn
        :return StsToken: 临时用户密钥
        """
        clt = client.AcsClient(access_key_id, access_key_secret, 'cn-hangzhou')
        req = AssumeRoleRequest.AssumeRoleRequest()

        req.set_accept_format('json')
        req.set_RoleArn(role_arn)
        req.set_RoleSessionName('oss-python-sdk-example')

        body = clt.do_action_with_exception(req)

        j = json.loads(oss2.to_unicode(body))

        token = StsToken()

        token.access_key_id = j['Credentials']['AccessKeyId']
        token.access_key_secret = j['Credentials']['AccessKeySecret']
        token.security_token = j['Credentials']['SecurityToken']
        token.request_id = j['RequestId']
        token.expiration = oss2.utils.to_unixtime(
            j['Credentials']['Expiration'], '%Y-%m-%dT%H:%M:%SZ')

        return token
        def get_fake_credentials_content(access_key_id, access_key_secret,
                                         role_arn, oss_region):
            clt = client.AcsClient(access_key_id, access_key_secret,
                                   oss_region)
            req = AssumeRoleRequest.AssumeRoleRequest()

            req.set_accept_format('json')
            req.set_RoleArn(role_arn)
            req.set_RoleSessionName('oss-python-sdk-fake-ecs-credentials-test')

            body = clt.do_action_with_exception(req)

            j = json.loads(oss2.to_unicode(body))
            credentials = dict()
            credentials['AccessKeyId'] = oss2.to_string(
                j['Credentials']['AccessKeyId'])
            credentials['AccessKeySecret'] = oss2.to_string(
                j['Credentials']['AccessKeySecret'])
            credentials['SecurityToken'] = oss2.to_string(
                j['Credentials']['SecurityToken'])
            credentials['Expiration'] = oss2.to_string(
                j['Credentials']['Expiration'])
            credentials['Code'] = 'Success'
            if random.choice([True, False]):
                credentials['LastUpdated'] = datetime.datetime.utcnow(
                ).strftime("%Y-%m-%dT%H:%M:%SZ")

            credentials = str(credentials)
            credentials_content = credentials.replace("'", '"')
            return credentials_content
    def test_sts(self):
        helloWorld = 'test_invoke_hello_world_' + ''.join(
            random.choice(string.ascii_lowercase) for _ in range(8))
        logging.info('create function: {0}'.format(helloWorld))
        self.client.create_function(
            self.serviceName,
            helloWorld,
            handler='main.my_handler',
            runtime='python2.7',
            codeZipFile='test/hello_world/hello_world.zip')

        sts_client = AliyunSDK.AcsClient(os.environ['ACCESS_KEY_ID'],
                                         os.environ['ACCESS_KEY_SECRET'],
                                         'cn-shanghai')
        request = AssumeRoleRequest.AssumeRoleRequest()
        request.set_RoleArn(os.environ['STS_ROLE'])
        request.set_RoleSessionName('fc-python-sdk')
        response = sts_client.do_action_with_exception(request)
        resp = json.loads(response)
        client = fc2.Client(
            endpoint=os.environ['ENDPOINT'],
            accessKeyID=resp['Credentials']['AccessKeyId'],
            accessKeySecret=resp['Credentials']['AccessKeySecret'],
            securityToken=resp['Credentials']['SecurityToken'],
        )
        r = client.invoke_function(self.serviceName, helloWorld)
        self.assertEqual(r.data.decode('utf-8'), 'hello world')
        self.client.delete_function(self.serviceName, helloWorld)
示例#4
0
    def fetch_sts_token(self):
        """子用户角色扮演获取临时用户的密钥
        :param access_key_id: 子用户的 access key id
        :param access_key_secret: 子用户的 access key secret
        :param role_arn: STS角色的Arn
        :return StsToken: 临时用户密钥
        """
        clt = client.AcsClient(MeFileConfig.access_key_id, MeFileConfig.access_key_secret, MeFileConfig.region_id)
        req = AssumeRoleRequest.AssumeRoleRequest()

        req.set_accept_format('json')
        req.set_RoleArn(MeFileConfig.sts_role_arn)
        req.set_RoleSessionName(MeFileConfig.role_session_name)

        body = clt.do_action_with_exception(req)
        print body
        j = json.loads(body)

        token = {
            'access_key_id': j['Credentials']['AccessKeyId'],
            'access_key_secret': j['Credentials']['AccessKeySecret'],
            'expiration': oss2.utils.to_unixtime(j['Credentials']['Expiration'], '%Y-%m-%dT%H:%M:%SZ'),
            'security_token': j['Credentials']['SecurityToken'],
            'bucket': MeFileConfig.bucket_name,
            'region_id': "oss-"+MeFileConfig.region_id,
            "platform":MeFileConfig.platform,
            "system_time":int(time.time()*1000)
        }
        return token
示例#5
0
    def fetch_sts_token(self):
        """子用户角色扮演获取临时用户的密钥
        :param access_key_id: 子用户的 access key id
        :param access_key_secret: 子用户的 access key secret
        :param role_arn: STS角色的Arn
        :return StsToken: 临时用户密钥
        """
        self.assert_param()
        clt = client.AcsClient(self.access_key_id, self.access_key_secret,
                               'cn-beijing')
        req = AssumeRoleRequest.AssumeRoleRequest()

        req.set_accept_format('json')
        req.set_RoleArn(self.sts_role_arn)
        req.set_RoleSessionName('cm-web-upload')
        req.set_DurationSeconds(900)

        body = clt.do_action(req)

        j = json.loads(body)

        self.token = StsToken()

        self.token.access_key_id = j['Credentials']['AccessKeyId']
        self.token.access_key_secret = j['Credentials']['AccessKeySecret']
        self.token.security_token = j['Credentials']['SecurityToken']
        self.token.request_id = j['RequestId']
        self.token.expiration = oss2.utils.to_unixtime(
            j['Credentials']['Expiration'], '%Y-%m-%dT%H:%M:%SZ')
        return self.token.access_key_id, self.token.access_key_secret, self.token.security_token
示例#6
0
def getStsToken(accessKeyId, accessKeySecret, roleArn, sessionName):
    clt = client.AcsClient(accessKeyId, accessKeySecret, 'cn-hangzhou')
    request = AssumeRoleRequest.AssumeRoleRequest()
    request.set_RoleArn(roleArn)
    request.set_RoleSessionName(sessionName)
    request.set_accept_format('json')
    response = clt.do_action(request)
    return json.loads(response)
示例#7
0
    def createStsToken(self):

        clt = client.AcsClient(self.stsAccessKeyID, self.stsAccessKeySecret,
                               self.regionId)
        # clt = client.AcsClient('HReEC1sQufBRLcQC', '5rqWY7jXhGeF0HBhYpl10mSkgrrHZt', 'cn-hangzhou')
        request = AssumeRoleRequest.AssumeRoleRequest()
        # 指定角色
        request.set_RoleArn('acs:ram::1406019938967626:role/tenderputrole')
        # 设置会话名称,审计服务使用此名称区分调用者
        request.set_RoleSessionName('tenderPutRole')

        # 发起请求,并得到response
        response = clt.do_action(request)

        info = xmltodict.parse(response)
        AssumeRoleResponse = info['AssumeRoleResponse']
        Credentials = AssumeRoleResponse['Credentials']
        AccessKeySecret = Credentials['AccessKeySecret']
        AccessKeyId = Credentials['AccessKeyId']
        Expiration = Credentials['Expiration']
        SecurityToken = Credentials['SecurityToken']
        now = datetime.now()

        tokenID = self.generateID(SecurityToken)

        # UTC 转换为 本地时间
        # UTC Zone
        from_zone = tz.gettz('UTC')
        # China Zone
        to_zone = tz.gettz('CST')

        utc = datetime.strptime(
            str(Expiration).replace('T', ' ').replace('Z', ''),
            "%Y-%m-%d %H:%M:%S")
        utc = utc.replace(tzinfo=from_zone)

        # Convert time zone
        local = utc.astimezone(to_zone)
        local = datetime.strftime(local, "%Y-%m-%d %H:%M:%S")

        try:
            db.session.query(StsToken).delete(synchronize_session=False)
            stsToken = StsToken(tokenID=tokenID,
                                AccessKeySecret=AccessKeySecret,
                                AccessKeyId=AccessKeyId,
                                Expiration=local,
                                SecurityToken=SecurityToken,
                                createTime=now)
            db.session.add(stsToken)
            db.session.commit()
        except Exception as e:
            print e
            traceback.print_exc()
            errorInfo = ErrorInfo['TENDER_02']
            errorInfo['detail'] = str(e)
            db.session.rollback()
            return (False, errorInfo)
示例#8
0
def get_token():

    # 构造"AssumeRole"请求
    ali_request = AssumeRoleRequest.AssumeRoleRequest()
    # 指定角色
    ali_request.set_RoleArn(RoleArn)
    # 设置会话名称,审计服务使用此名称区分调用者
    ali_request.set_RoleSessionName(Role)
    # 发起请求,并得到response
    ali_response = clt.do_action_with_exception(ali_request)
    return ali_response
示例#9
0
 def get_sts_token(self):
     clt = client.AcsClient(self.access_key_id, self.access_key_secret,
                            self.region)
     request = AssumeRoleRequest.AssumeRoleRequest()
     request.set_accept_format('json')
     request.set_RoleArn(self.role_arn)
     request.set_RoleSessionName(self.role_session_name)
     request.set_DurationSeconds(self.duration_seconds)
     response = clt.do_action(request)
     res_dict = json.loads(response)
     credentials = res_dict['Credentials']
     return credentials
示例#10
0
def _getSTStoken(session_name):
    clt = client.AcsClient('LTAItm7fS9L6UV2R','K9WF2FzfBHK6szZL1hb6JOQcn5yCfp','cn-beijing')
    # 构造"AssumeRole"请求
    request = AssumeRoleRequest.AssumeRoleRequest()
    # 指定角色
    request.set_RoleArn('acs:ram::1035891576597919:role/myblog-role')
    # 设置会话名称,审计服务使用此名称区分调用者
    request.set_RoleSessionName(session_name)

    # 发起请求,并得到response
    response = clt.do_action_with_exception(request)

    return json.loads(response)
    def get_sts(self):
        clt = client.AcsClient(OSS_STS_ID, OSS_STS_KEY, OSS_REGION)
        req = AssumeRoleRequest.AssumeRoleRequest()

        req.set_accept_format('json')
        req.set_RoleArn(OSS_STS_ARN)
        req.set_RoleSessionName('oss-python-sdk-example')

        body = clt.do_action_with_exception(req)

        j = json.loads(oss2.to_unicode(body))

        return j['Credentials']['AccessKeyId'], j['Credentials'][
            'AccessKeySecret'], j['Credentials']['SecurityToken']
示例#12
0
def getSts():

    # 通过管理控制后台-访问控制 https://help.aliyun.com/product/28625.html
    # RAM控制台 https://ram.console.aliyun.com/
    # STS授权相关信息获取步骤:
    # 1.RAM控制台用户管理创建子用户(User)同时点击该用户创建并获取AccessKeyID和AccessKeySecret https://help.aliyun.com/document_detail/28637.html
    # 2.对该子用户(User) 授予AliyunSTSAssumeRoleAccess策略(必须),如需自定义策略请看 https://help.aliyun.com/document_detail/28640.html
    # 3.RAM控制台角色管理创建角色role,进行自定义授权设置(控制操作的内容),获取Arn https://help.aliyun.com/document_detail/28649.html
    # 注意点:
    # 只有子用户(User)才能调用 AssumeRole 接口
    # 阿里云主用户(Root User)的AccessKeys不能用于发起AssumeRole请求
    # python sdk说明
    # 构建一个 Aliyun Client, 用于发起请求
    # 构建Aliyun Client时需要设置AccessKeyId和AccessKeySevcret
    # STS是Global Service, API入口位于华东 1 (杭州) , 这里Region填写"cn-hangzhou"
    # clt = client.AcsClient('<access-key-id>','<access-key-secret>','cn-hangzhou')
    AccessKeyID = "************************"
    AccessKeySecret = "************************"
    roleArn = "************************"
    clt = client.AcsClient(AccessKeyID, AccessKeySecret, 'cn-hangzhou')
    # 构造"AssumeRole"请求
    request = AssumeRoleRequest.AssumeRoleRequest()
    # 指定角色 需要在 RAM 控制台上获取
    request.set_RoleArn(roleArn)
    # RoleSessionName 是临时Token的会话名称,自己指定用于标识你的用户,主要用于审计,或者用于区分Token颁发给谁
    # 但是注意RoleSessionName的长度和规则,不要有空格,只能有'-' '.' '@' 字母和数字等字符
    # 具体规则请参考API文档中的格式要求
    request.set_RoleSessionName('al001')

    #OSS Policy settings  could not set by default
    #can read https://help.aliyun.com/document_detail/56288.html
    #case https://help.aliyun.com/knowledge_detail/39717.html?spm=5176.product28625.6.735.5etPTf
    #case https://help.aliyun.com/knowledge_detail/39712.html?spm=5176.7739717.6.729.aZiRgD
    # 发起请求,并得到response
    try:
        response = clt.do_action_with_exception(request)
        text = json.loads(response)
        stsDict = text["Credentials"]
        stsDict["StatusCode"] = "200"
        stsText = json.dumps(stsDict)
    except Exception as e:
        errorDict = dict().fromkeys(
            ['StatusCode', 'ErrorCode', 'ErrorMessage'])
        errorDict["StatusCode"] = "500"
        errorDict["ErrorMessage"] = e.message
        errorDict["ErrorCode"] = e.error_code
        stsText = json.dumps(errorDict)
    return stsText
    pass
示例#13
0
def oss_auth():
    access_key_id = app.config['OSS_ACCESS_KEY_ID']
    access_key_secret = app.config['OSS_ACCESS_KEY_SECRET']
    bucket_name = app.config['OSS_BUCKET_NAME']
    role_arn = app.config['OSS_ROLE_ARN']

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

    req.set_accept_format('json')
    req.set_RoleArn(role_arn)
    req.set_RoleSessionName('python-face-recognition')
    body = clt.do_action(req)

    return Response(body, mimetype='application/json')
示例#14
0
    def get_token(self):
        # args = parameter_required(("id", ))
        from aliyunsdkcore import client
        from aliyunsdksts.request.v20150401 import AssumeRoleRequest
        import json
        # 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录RAM控制台创建RAM账号。
        # role_arn为角色的资源名称。
        from jinrui.config.secret import ACCESS_KEY_ID_STS, ACCESS_KEY_SECRET_STS, ACCESS_KEY_ROLE_ARN
        # 创建policy_text。
        # 仅允许对名称为test-bucket1的Bucket下的所有资源执行GetObject操作。
        policy_text = """
        {
            "Version": "1", 
            "Statement": [
                {
                    "Action": ["sts:AssumeRole"], 
                    "Effect": "Allow", 
                    "Resource": "*"
                },
                {
                    "Action": "oss:*",
                    "Effect": "Allow",
                    "Resource": "*"
                }
            ]
        }
        """
        clt = client.AcsClient(ACCESS_KEY_ID_STS, ACCESS_KEY_SECRET_STS, 'cn-hangzhou')
        req = AssumeRoleRequest.AssumeRoleRequest()

        # 设置返回值格式为JSON。
        req.set_accept_format('json')
        req.set_RoleArn(ACCESS_KEY_ROLE_ARN)
        req.set_RoleSessionName('session-name')
        req.set_Policy(policy_text)
        body = clt.do_action_with_exception(req)

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

        return {
            "code": 200,
            "success": True,
            "message": "获取成功",
            "data": token
        }
示例#15
0
def fetch_sts_token(access_key_id, access_key_secret, role_arn):
    clt = client.AcsClient(access_key_id, access_key_secret, "cn-hangzhou")
    req = AssumeRoleRequest.AssumeRoleRequest()

    req.set_accept_format("json")
    req.set_RoleArn(role_arn)
    req.set_RoleSessionName("oss-python-sdk-example")

    body = clt.do_action_with_exception(req)

    j = json.loads(oss2.to_unicode(body))

    access_key_id = j["Credentials"]["AccessKeyId"]
    access_key_secret = j["Credentials"]["AccessKeySecret"]
    security_token = j["Credentials"]["SecurityToken"]

    return access_key_id, access_key_secret, security_token
示例#16
0
文件: oss.py 项目: hpf0532/corona
def get_sts_token():
    """
    获取sts临时token
    :return:
    """
    clt = client.AcsClient(current_app.config['ACCESS_KEY_ID'],
                           current_app.config['ACCESS_KEY_SECRET'],
                           current_app.config['STS_REGION'])
    req = AssumeRoleRequest.AssumeRoleRequest()

    # 设置返回值格式为JSON。
    req.set_accept_format('json')
    req.set_RoleArn(current_app.config['ROLE_ARN'])
    req.set_RoleSessionName('session-name')
    req.set_DurationSeconds(900)
    body = clt.do_action_with_exception(req)

    # 使用RAM账号的AccessKeyId和AccessKeySecret向STS申请临时token。
    token = json.loads(body)
    return token
示例#17
0
    def _get_token(self, conf, session_name):
        session_name = "{}{}".format(session_name, random.randint(1, 10000))
        clt = client.AcsClient(conf.sts.id, conf.sts.secret, conf.sts.area)
        req = AssumeRoleRequest.AssumeRoleRequest()

        req.set_accept_format('json')
        req.set_RoleArn(conf.sts.arn)
        req.set_RoleSessionName(session_name)
        req.set_DurationSeconds(1200)

        body = clt.do_action_with_exception(req)
        try:
            token = json.loads(body)
        except Exception as e:
            MailSender.send('oss get sts token is error, e: {}'.format(e))
            self.token = self.auth = None
            if not os.path.exists(conf.sts.temp):
                os.mkdir(conf.sts.temp)
        else:
            return token
示例#18
0
    def fetch_sts_token(access_key_id, access_key_secret, role_arn):
        clt = client.AcsClient(access_key_id, access_key_secret, OSS_REGION)
        req = AssumeRoleRequest.AssumeRoleRequest()

        req.set_accept_format('json')
        req.set_RoleArn(role_arn)
        req.set_RoleSessionName('oss-python-sdk-test')

        body = clt.do_action_with_exception(req)

        j = json.loads(oss2.to_unicode(body))

        token = StsToken()

        token.access_key_id = j['Credentials']['AccessKeyId']
        token.access_key_secret = j['Credentials']['AccessKeySecret']
        token.security_token = j['Credentials']['SecurityToken']
        token.request_id = j['RequestId']
        token.expiration = oss2.utils.to_unixtime(j['Credentials']['Expiration'], '%Y-%m-%dT%H:%M:%SZ')

        return token
示例#19
0
def gen_signature(allow_prefix=None,
                  SecretId=SECRET_ID,
                  SecretKey=SECRET_KEY,
                  expire=300,
                  bucket=BUCKET,
                  method='GET',
                  session_name='nobody'):
    # endpoint = 'http://oss-%s.aliyuncs.com' % AP
    clt = client.AcsClient(SecretId, SecretKey, AP)

    policy_text = """{
            "Version": "1", 
            "Statement": [
              {"Action": ["oss:GetObject","oss:PutObject"], 
                "Effect": "Allow", 
                "Resource": ["acs:oss:*:*:%s/%s"]
              }
            ]
        }""" % (bucket, allow_prefix)
    # print(policy_text)

    req = AssumeRoleRequest.AssumeRoleRequest()
    req.set_accept_format('json')
    req.set_RoleArn(ROLE)
    req.set_RoleSessionName(session_name)
    req.set_Policy(policy_text)
    body = clt.do_action_with_exception(req)
    d = json.loads(oss2.to_unicode(body))

    # auth = oss2.StsAuth(token['Credentials']['AccessKeyId'],
    #                     token['Credentials']['AccessKeySecret'],
    #                     token['Credentials']['SecurityToken'])

    #
    # auth = oss2.Auth(SecretId, SecretKey)
    # the_bucket = oss2.Bucket(auth, endpoint, bucket)
    # surl = the_bucket.sign_url(method, allow_prefix, expire)
    d['region'] = 'oss-%s' % AP
    d['bucket'] = bucket
    return d
示例#20
0
def fetch_sts_info(access_key_id, access_key_secret, sts_role_arn):
    """子用户角色扮演获取临时用户的密钥
    :param access_key_id: 子用户的 access key id
    :param access_key_secret: 子用户的 access key secret
    :param sts_role_arn: STS角色的Arn
    :return StsInfo 返回授权用户信息对象
    """
    # 配置要访问的STS endpoint
    _REGIONID = 'cn-hongkong'
    _ENDPOINT = 'sts.cn-hongkong.aliyuncs.com'
    region_provider.add_endpoint('Sts', _REGIONID, _ENDPOINT)

    clt = client.AcsClient(access_key_id, access_key_secret, 'cn-hongkong')
    request = AssumeRoleRequest.AssumeRoleRequest()

    #request.set_accept_format('json')
    #指定角色ARN
    request.set_RoleArn(sts_role_arn)
    #设置会话名称,审计服务使用此名称区分调用者
    request.set_RoleSessionName('oss-python-sdk-example')
    #设置临时身份过期时间
    request.set_DurationSeconds(DurationSeconds)
    #发起请求,并得到response
    response = clt.do_action_with_exception(request)
    #格式化输出返回结果,将字符串结果转化为字典类型
    i = json.loads(oss2.to_unicode(response))
    #实例化StsInfo类并将临时用户信息存入对象
    global StsInfo
    StsInfo = StsInfo()
    StsInfo.access_key_id = i['Credentials']['AccessKeyId']
    StsInfo.access_key_secret = i['Credentials']['AccessKeySecret']
    StsInfo.security_token = i['Credentials']['SecurityToken']
    StsInfo.request_id = i['RequestId']
    StsInfo.expiration = oss2.utils.to_unixtime(i['Credentials']['Expiration'],
                                                '%Y-%m-%dT%H:%M:%SZ')

    #存储临时用户信息
    save_info()
示例#21
0
async def get_sts_token(role_arn):
    """
    通过role_arn获取token
    :param role_arn:
    :return:
    """
    # endpoint = OSS_ENDPOINT
    # bucket_name = OSS_BUCKET_NAME
    # 子账号AccessKeyId
    access_key_id = OSS_ACCESS_KEY_ID
    # 子账号AccessKeySecret
    access_key_secret = OSS_ACCESS_KEY_SECRET
    clt = client.AcsClient(access_key_id, access_key_secret, OSS_REGION_ID)
    req = AssumeRoleRequest.AssumeRoleRequest()
    # 为了简化讨论,这里没有设置Duration、Policy等,更多细节请参考RAM、STS的相关文档。
    req.set_accept_format('json')  # 设置返回值格式为JSON
    req.set_RoleArn(role_arn)
    req.set_RoleSessionName('session-name')
    req.set_DurationSeconds(1800)  # 半小时过期时间
    body = clt.do_action_with_exception(req)
    # 为了简化讨论,没有做出错检查
    token = json.loads(body.decode('utf-8'))
    return token['Credentials']
示例#22
0
 def __init__(self, OSS_OPTION):  # 重写init方法
     # 获取AccessKeyId和AccessKeySecret和临时token
     accessKeyId = OSS_OPTION['AK_ID']
     accessKeySecret = OSS_OPTION['AK_SE']
     self.bucketName = OSS_OPTION['BUCKET_NAME']
     cn = OSS_OPTION['CN']
     roleArn = OSS_OPTION['roleArn']
     clt = client.AcsClient(accessKeyId, accessKeySecret, cn)
     req = AssumeRoleRequest.AssumeRoleRequest()
     policyText = '{"Version": "1", "Statement": [{"Action": ["oss:PutObject", "oss:GetObject"], ' \
                   '"Effect": "Allow", "Resource": ["acs:oss:*:*:' + self.bucketName + '/*"]}]}'
     # 设置返回值格式为JSON。
     req.set_accept_format('json')
     req.set_RoleArn(roleArn)
     req.set_RoleSessionName('session-name')
     req.set_Policy(policyText)
     body = clt.do_action_with_exception(req)
     # 使用RAM账号的AccessKeyId和AccessKeySecret向STS申请临时token。
     self.token = json.loads(oss2.to_unicode(body))
     self.AccessKeyId = self.token['Credentials']['AccessKeyId']
     self.AccessKeySecret = self.token['Credentials']['AccessKeySecret']
     self.SecurityToken = self.token['Credentials']['SecurityToken']
     self._connectOss()  # 链接oss数据库
示例#23
0
def get_oss_client(context, endpoint, bucket, access_role=None):
    creds = context.credentials
    key_id, key_secret, token = creds.access_key_id, creds.access_key_secret, creds.security_token
    local = bool(os.getenv('local', ""))
    if access_role:
        req = AssumeRoleRequest.AssumeRoleRequest()
        req.set_accept_format('json')
        req.set_RoleArn(access_role)
        req.set_RoleSessionName('oss-copy')

        if local:
            acs_creds1 = AccessKeyCredential(creds.access_key_id,
                                             creds.access_key_secret)
        else:
            acs_creds1 = StsTokenCredential(creds.access_key_id,
                                            creds.access_key_secret,
                                            creds.security_token)
            # Since the function instance runs within VPC (FC system), the endpoint has to be either public or vpc endpoint.
            # Here the VPC endpoint is used because it's more secure, latency is low and no public network usage is incurred.
            req.set_endpoint('sts-vpc.%s.aliyuncs.com' % (context.region))
        # Create clt1 with temp credentials provided by fc context
        clt = client.AcsClient(region_id=context.region, credential=acs_creds1)
        body1 = clt.do_action(req)
        ar_resp1 = json.loads(body1)
        # Now we get another temp credentials
        tmp_creds2 = ar_resp1['Credentials']
        key_id, key_secret, token = tmp_creds2['AccessKeyId'], tmp_creds2[
            'AccessKeySecret'], tmp_creds2['SecurityToken']
        auth = oss2.StsAuth(key_id, key_secret, token)
    else:
        if local:
            auth = oss2.Auth(key_id, key_secret)
        else:
            auth = oss2.StsAuth(key_id, key_secret, token)
            # for local testing, use the public endpoint
    endpoint = str.replace(endpoint, "-internal", "") if local else endpoint
    return oss2.Bucket(auth, endpoint, bucket)
示例#24
0
from aliyunsdkcore import client
from aliyunsdksts.request.v20150401 import AssumeRoleRequest
import json
import oss2
from itertools import islice

endpoint = 'oss-cn-beijing.aliyuncs.com'
bucket_name = 'mooc-feng'
# 子账号AccessKeyId
access_key_id = 'LTAIdCYLSKnUsb37'
# 子账号AccessKeySecret
access_key_secret = '65TpH3XXEdJSdHJuruQyZoaplqeK4q'
# 角色的资源描述符  只拥有只读权限的角色
role_arn = 'acs:ram::1363311981980278:role/moocfengappreadonly'
clt = client.AcsClient(access_key_id, access_key_secret, 'cn-beijing')
req = AssumeRoleRequest.AssumeRoleRequest()
# 为了简化讨论,这里没有设置Duration、Policy等,更多细节请参考RAM、STS的相关文档。
req.set_accept_format('json')  # 设置返回值格式为JSON
req.set_RoleArn(role_arn)
req.set_RoleSessionName('session-name')
req.set_DurationSeconds(1800)  # 半小时过期时间
body = clt.do_action_with_exception(req)
# 为了简化讨论,没有做出错检查
token = json.loads(body)

# ---------将token给客户端-----------------

# 初始化StsAuth实例
auth = oss2.StsAuth(token['Credentials']['AccessKeyId'],
                    token['Credentials']['AccessKeySecret'],
                    token['Credentials']['SecurityToken'])