All Products
Search
Document Center

Alibaba Cloud SDK:Initialize an SDK client by using an STS token

Last Updated:Jul 09, 2024

This topic describes how to use a Security Token Service (STS) token to initialize an SDK client in Alibaba Cloud SDK V1.0 for Node.js.

Install STS SDK

npm install @alicloud/sts-sdk
Important

The version of Node.js must be 8.5.0 or later.

Example

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


async function main() {
    try {
        // Initialize the STS client.
        const sts = new StsClient({
            endpoint: 'sts.aliyuncs.com',
            // Obtain the AccessKey ID of the Resource Access Management (RAM) user from an environment variable.
            accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
            // Obtain the AccessKey secret of the RAM user from an environment variable.
            accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
        });

        const roleArn = 'ram_role_arn'; // The Alibaba Cloud Resource Name (ARN) of the RAM role.
        const roleSessionName = 'role_session_name'; // The name of the role session.
        const durationSeconds = 3600; // The validity period of the role session, in seconds.
        const policy = ''; // The permission policy.

        // Call the assumeRole operation to obtain the STS token.
        const assumeRoleResponse = await sts.assumeRole(roleArn, roleSessionName, policy, durationSeconds);
        const credentials = assumeRoleResponse.Credentials;

        // Use the STS token to initialize an SDK client of the remote procedure call (RPC) style.
        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();