通过STS Token初始化客户端

更新时间:

本文为您介绍如何通过STS Token初始化客户端。

安装

npm install @alicloud/sts-sdk
重要

Node.js的版本 >= 8.5.0。

示例

const StsClient = require('@alicloud/sts-sdk');
const RPCClient = require('@alicloud/pop-core').RPCClient;


async function main() {
    try {
        // 初始化STS客户端
        const sts = new StsClient({
            endpoint: 'sts.aliyuncs.com',
            // 从环境变量中获取RAM用户的AccessKey ID
            accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
            // 从环境变量中获取RAM用户的AccessKey Secret
            accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
        });

        const roleArn = 'ram_role_arn'; // 角色ARN
        const roleSessionName = 'role_session_name'; // 角色会话名称
        const durationSeconds = 3600; // 角色会话过期时间
        const policy = ''; // 权限策略

        // 调用assumeRole服务获取STS Token
        const assumeRoleResponse = await sts.assumeRole(roleArn, roleSessionName, policy, durationSeconds);
        const credentials = assumeRoleResponse.Credentials;

        // 使用STS Token初始化RPC客户端
        const client = new RPCClient({
            accessKeyId: credentials.AccessKeyId,
            accessKeySecret: credentials.AccessKeySecret,
            securityToken: credentials.SecurityToken,
            endpoint: 'https://ecs.cn-beijing.aliyuncs.com',
            apiVersion: '2014-05-26',
        });

        const params = {};
        const action = 'DescribeRegions';
        const result = await client.request(action, params);
        console.log(JSON.stringify(result));
    } catch (err) {
        console.error('An error occurred:', err);
    }
}

main();