Manage access credentials

更新时间:
复制 MD 格式

The Alibaba Cloud SDK uses the Credentials tool to centrally manage credentials, such as your AccessKey and STS Token. This topic describes the supported credential types and their configuration methods.

Background

Credentials verify a user's identity when accessing Alibaba Cloud services. Common credential types include:

  1. An AccessKey pair provides permanent credentials for an Alibaba Cloud account or a RAM user. It consists of an AccessKey ID and an AccessKey Secret.

  2. An STS token provides temporary credentials for a RAM role with a configurable validity period and permission scope. What is STS.

  3. A bearer token is used for authentication and authorization.

Prerequisites

Install the Credentials tool

Run the following npm command to install the package.

npm install @alicloud/credentials

Use the latest version to ensure all credential types are supported. Releases · aliyun/credentials-nodejs · GitHub.

Credential parameters

Configure credentials through the @alicloud/credentials module's Config constructor. The type parameter is required and determines which other parameters apply. The following table lists the valid type values and their parameters. = required, - = optional, × = unsupported.

Note

Only the credential types and parameters listed below are supported.

type

access_key

sts

ram_role_arn

ecs_ram_role

oidc_role_arn

credentials_uri

bearer

accessKeyId: The AccessKey ID.

×

×

×

×

accessKeySecret: The AccessKey secret.

×

×

×

×

securityToken: The Security Token Service (STS) token.

×

-

×

×

×

×

roleArn: The Alibaba Cloud Resource Name (ARN) of the RAM role.

×

×

×

×

×

roleSessionName: A custom name for the session. The default format is credentials-nodejs-<timestamp>.

×

×

-

×

-

×

×

roleName: The name of the RAM role.

×

×

×

-

×

×

×

disableIMDSv1: Specifies whether to enforce the security hardening mode (IMDSv2). Default value: false.

×

×

×

-

×

×

×

bearerToken: The bearer token.

×

×

×

×

×

×

policy: A custom policy.

×

×

-

×

-

×

×

roleSessionExpiration: The session expiration time, in seconds. Default value: 3600.

×

×

-

×

-

×

×

oidcProviderArn: The ARN of the OpenID Connect (OIDC) identity provider.

×

×

×

×

×

×

oidcTokenFilePath: The path to the OpenID Connect (OIDC) token file.

×

×

×

×

×

×

externalId: An external ID to mitigate the confused deputy problem. Use an external ID to prevent the confused deputy problem.

×

×

-

×

×

×

×

credentialsURI: The URI of the credentials.

×

×

×

×

×

×

The STS endpoint. Supports both VPC and public endpoints. Available endpoints: Endpoints. Default: sts.aliyuncs.com.

×

×

-

×

-

×

×

timeout: The read timeout for HTTP requests, in milliseconds. The default value is 5000.

×

×

-

-

-

-

×

connectTimeout: The connection timeout for HTTP requests, in milliseconds. The default value is 10000.

×

×

-

-

-

-

×

Initialize a credentials client

The previous section describes the credential types and configuration parameters supported by the Credentials tool. The following sections provide code examples showing how to use the tool. Select the method that best fits your scenario.

Important
  • Never store an AccessKey in plaintext in your project code. An exposed key compromises all resources under the account. Store it in environment variables or configuration files instead.

  • Implement the singleton pattern for the credentials tool. This enables the built-in credential cache, preventing rate limiting from excessive API calls. Credential auto-refresh mechanism for session credentials.

Method 1: Default credential provider chain

Initializing a credentials client without parameters activates the Default credential provider chain.

const Credential = require('@alicloud/credentials');
// Use the default credential provider chain
const credentialClient = new Credential.default();
const credential = credentialClient.getCredential();
credential.then(credential => {
    console.log(credential);
});
import Credential from '@alicloud/credentials';
const credential = new Credential();
credential.getCredential().then(credential => {
    console.log(credential);
});

API call

This example shows how to call the DescribeRegions operation of ECS. To run the code, you must install the ECS SDK.

const Ecs20140526 = require('@alicloud/ecs20140526');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Credential = require('@alicloud/credentials');
async function main() {
    // Initialize the credential client with default credentials.
    const credentialClient = new Credential.default();
    const ecsConfig = new OpenApi.Config({
        endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // Configure the service endpoint.
        credential: credentialClient, // Specify the credential client.
    });
    const ecsClient = new Ecs20140526.default(ecsConfig);
    const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
    const runtime = new Util.RuntimeOptions();
    ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime).then((result) => {
        console.log(JSON.stringify(result.body));
    });
}
main().catch(console.error);
import Ecs20140526, * as $Ecs20140526 from '@alicloud/ecs20140526';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';
import Credential from '@alicloud/credentials';
export default class Client {
    static async main(): Promise<$Ecs20140526.DescribeRegionsResponse> {
        // Initialize a credential instance with default credentials.
        let credential = new Credential();
        let config = new $OpenApi.Config({
            credential: credential, // Specify the credential instance.
            endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // Configure the service endpoint.
        });
        let client = new Ecs20140526(config);
        let describeRegionsRequest = new $Ecs20140526.DescribeRegionsRequest({});
        let runtime = new $Util.RuntimeOptions({});
        return await client.describeRegionsWithOptions(describeRegionsRequest, runtime);
    }
}
const response = Client.main();
response.then(res => {
    console.log(res.body?.regions);
});

Method 2: Use an AccessKey

The Credentials tool uses the AccessKey you provide as the access credential.

Warning

An Alibaba Cloud account (root account) has full permissions over all its resources, so an exposed AK poses a significant security risk. Do not use the AK of a root account.

Use the AK of a RAM user with least-privilege permissions.

const Credential = require('@alicloud/credentials');
const credentialsConfig = new Credential.Config({
    // The credential type.
    type: 'access_key',
    // Your AccessKey ID, retrieved from an environment variable.
    accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
    // Your AccessKey Secret, retrieved from an environment variable.
    accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
});
const credentialClient = new Credential.default(credentialsConfig);
import Credential, { Config } from '@alicloud/credentials';
const credentialsConfig  = new Config({
    // The credential type.
    type: 'access_key',
    // Your AccessKey ID, retrieved from an environment variable.
    accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
    // Your AccessKey Secret, retrieved from an environment variable.
    accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
});
const credentialClient = new Credential(credentialsConfig);

API call

This example calls the DescribeRegions operation of ECS. You must install the ECS SDK to run the code.

const Ecs20140526 = require('@alicloud/ecs20140526');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Credential = require('@alicloud/credentials');
async function main() {
    const credentialsConfig = new Credential.Config({
        // The credential type.
        type: 'access_key',
        // The AccessKey ID, read from an environment variable.
        accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
        // The AccessKey secret, read from an environment variable.
        accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
    });
    const credentialClient = new Credential.default(credentialsConfig);
    const ecsConfig = new OpenApi.Config();
    ecsConfig.endpoint = 'ecs.cn-hangzhou.aliyuncs.com'; // The service endpoint.
    ecsConfig.credential = credentialClient; // The credential client for authentication.
    const ecsClient = new Ecs20140526.default(ecsConfig);
    const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
    const runtime = new Util.RuntimeOptions();
    ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime).then((response) => {
        console.log(response.body.regions);
    });
}
main().catch(console.error);
import Ecs20140526, * as $Ecs20140526 from '@alicloud/ecs20140526';
import Credential, { Config } from '@alicloud/credentials';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';
export default class Client {
    static async main(): Promise<$Ecs20140526.DescribeRegionsResponse> {
        const credentialsConfig = new Config({
            // The credential type.
            type: 'access_key',
            // The AccessKey ID, read from an environment variable.
            accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
            // The AccessKey secret, read from an environment variable.
            accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
        });
        const credentialClient = new Credential(credentialsConfig);
        let config = new $OpenApi.Config({
            credential: credentialClient, // The credential client for authentication.
            endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The service endpoint.
        });
        let client = new Ecs20140526(config);
        let describeRegionsRequest = new $Ecs20140526.DescribeRegionsRequest({});
        let runtime = new $Util.RuntimeOptions({});
        return await client.describeRegionsWithOptions(describeRegionsRequest, runtime);
    }
}
const response = Client.main();
response.then(res => {
    console.log(res.body?.regions);
});

Method 3: Use an STS token

The Credentials tool uses the static STS token you provide as the access credential.

const Credential = require('@alicloud/credentials');
const credentialsConfig = new Credential.Config({
    type: 'sts',
    // Your AccessKey ID, retrieved from an environment variable.
    accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
    // Your AccessKey Secret, retrieved from an environment variable.
    accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
    // Your security token, retrieved from an environment variable.
    securityToken: process.env.ALIBABA_CLOUD_SECURITY_TOKEN,
});
const cred = new Credential.default(credentialsConfig);
import Credential, { Config } from '@alicloud/credentials';
const credentialsConfig = new Config({
    // The credential type.
    type: 'access_key',
    // Your AccessKey ID, retrieved from an environment variable.
    accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
    // Your AccessKey Secret, retrieved from an environment variable.
    accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
    // Your security token, retrieved from an environment variable.
    securityToken: process.env.ALIBABA_CLOUD_SECURITY_TOKEN,
});
const credentialClient = new Credential(credentialsConfig);

API call

This example calls the DescribeRegions operation of ECS. To run this code, you must install the ECS SDK and the Security Token Service SDK.

const Ecs20140526 = require('@alicloud/ecs20140526');
const Sts20150401 = require('@alicloud/sts20150401');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Credential = require('@alicloud/credentials');
async function assumeRole() {
    // Create an STS client to get an STS token.
    const stsConfig = new OpenApi.Config({
        endpoint: 'sts.cn-hangzhou.aliyuncs.com', // The endpoint for Security Token Service (STS).
        accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID, // Get the AccessKey ID from an environment variable.
        accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET, // Get the AccessKey secret from an environment variable.
    });
    const stsClient = new Sts20150401.default(stsConfig);
    const assumeRoleRequest = new Sts20150401.AssumeRoleRequest({
        durationSeconds: 3600, // The validity period of the STS token.
        roleArn: '<RoleArn>', // The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole. This can be set with the ALIBABA_CLOUD_ROLE_ARN environment variable. 
        roleSessionName: '<RoleSessionName>', // A custom name for the role session. This can be set with the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. 
        policy: '', // Optional. A RAM policy. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    });
    try {
        const assumeRoleResponsePromise = await stsClient.assumeRole(assumeRoleRequest);
        const assumeRoleResponseBodyCredentials = assumeRoleResponsePromise.body.credentials;
        return {
            accessKeyId: assumeRoleResponseBodyCredentials.accessKeyId,
            accessKeySecret: assumeRoleResponseBodyCredentials.accessKeySecret,
            securityToken: assumeRoleResponseBodyCredentials.securityToken,
        };
    } catch (error) {
        console.error('The AssumeRole request failed:', error);
        throw error;
    }
}
async function main() {
    const stsToken = await assumeRole()
    const credentialsConfig = new Credential.Config({
        // The type of credential.
        type: 'sts',
        accessKeyId: stsToken.accessKeyId,
        accessKeySecret: stsToken.accessKeySecret,
        securityToken: stsToken.securityToken,
    });
    const credentialClient = new Credential.default(credentialsConfig);
    const ecsConfig = new OpenApi.Config({
        endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The endpoint of the cloud service.
        credential: credentialClient, // The authentication credential.
    })
    const ecsClient = new Ecs20140526.default(ecsConfig);
    const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
    const runtime = new Util.RuntimeOptions();
    // Call the DescribeRegions operation.
    ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime).then((response) => {
        console.log(response.body.regions);
    });
}
main().catch(console.error);
import Ecs20140526, * as $Ecs20140526 from '@alicloud/ecs20140526';
import Sts20150401, * as $Sts20150401 from '@alicloud/sts20150401';
import OpenApi, { Config } from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';
import Credential, { Config as CredentialConfig } from '@alicloud/credentials';
async function assumeRole() {
    // Create an STS client to get an STS token.
    const stsConfig = new Config({
        endpoint: 'sts.cn-hangzhou.aliyuncs.com', // The endpoint for Security Token Service (STS).
        accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID, // Get the AccessKey ID from an environment variable.
        accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET, // Get the AccessKey secret from an environment variable.
    });
    const stsClient = new Sts20150401(stsConfig);
    const assumeRoleRequest = new $Sts20150401.AssumeRoleRequest({
        durationSeconds: 3600, // The validity period of the STS token.
        roleArn: '<RoleArn>', // The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole. This can be set with the ALIBABA_CLOUD_ROLE_ARN environment variable.  
        roleSessionName: '<RoleSessionName>', // A custom name for the role session. This can be set with the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. 
        policy: '', // Optional. A RAM policy. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    });
    try {
        const assumeRoleResponsePromise = await stsClient.assumeRole(assumeRoleRequest);
        const assumeRoleResponseBodyCredentials = assumeRoleResponsePromise.body?.credentials;
        return {
            accessKeyId: assumeRoleResponseBodyCredentials?.accessKeyId,
            accessKeySecret: assumeRoleResponseBodyCredentials?.accessKeySecret,
            securityToken: assumeRoleResponseBodyCredentials?.securityToken,
        };
    } catch (error) {
        console.error('The AssumeRole request failed:', error);
        throw error;
    }
}
async function main() {
    const stsToken = await assumeRole()
    const credentialsConfig = new CredentialConfig({
        // The type of credential.
        type: 'sts',
        accessKeyId: stsToken.accessKeyId,
        accessKeySecret: stsToken.accessKeySecret,
        securityToken: stsToken.securityToken,
    });
    const credentialClient = new Credential(credentialsConfig);
    const ecsConfig = new Config({
        endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The endpoint of the cloud service.
        credential: credentialClient, // The authentication credential.
    })
    const ecsClient = new Ecs20140526(ecsConfig);
    const describeRegionsRequest = new $Ecs20140526.DescribeRegionsRequest();
    const runtime = new $Util.RuntimeOptions();
    // Call the DescribeRegions operation.
    ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime).then((response) => {
        console.log(response.body?.regions);
    });
}
main().catch(console.error);

Method 4: AccessKey and RAM Role ARN

This method uses STS internally. When you specify a RAM role ARN, the Credentials tool obtains an STS token from STS. You can use the policy parameter to further restrict the role's permissions.

const Credential = require('@alicloud/credentials');
const credentialsConfig = new Credential.Config({
    type: 'ram_role_arn',
    accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
    accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
    // The RAM role ARN to assume. Example: acs:ram::123456789012****:role/adminrole. This can also be set using the `ALIBABA_CLOUD_ROLE_ARN` environment variable.
    roleArn: '<RoleArn>',
    // A custom role session name. This can also be set using the `ALIBABA_CLOUD_ROLE_SESSION_NAME` environment variable.
    roleSessionName: '<RoleSessionName>',
    // Optional. An inline policy to limit the permissions of the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    policy: '<Policy>',
    roleSessionExpiration: 3600,
});
const cred = new Credential.default(credentialsConfig);
import Credential, { Config } from '@alicloud/credentials';
const credentialsConfig = new Config({
    type: 'ram_role_arn',
    accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
    accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
    // The RAM role ARN to assume. Example: acs:ram::123456789012****:role/adminrole. This can also be set using the `ALIBABA_CLOUD_ROLE_ARN` environment variable.
    roleArn: '<RoleArn>',
    // A custom role session name. This can also be set using the `ALIBABA_CLOUD_ROLE_SESSION_NAME` environment variable.
    roleSessionName: '<RoleSessionName>',
    // Optional. An inline policy to limit the permissions of the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    policy: '<Policy>',
    roleSessionExpiration: 3600,
});
const credentialClient = new Credential(credentialsConfig);

API call method

This example shows how to call the DescribeRegions operation of ECS. To run the code, you must install the ECS SDK.

const Ecs20140526 = require('@alicloud/ecs20140526');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Credential = require('@alicloud/credentials');
async function main() {
    const credentialsConfig = new Credential.Config({
        // Specifies the credential type.
        type: 'ram_role_arn',
        // Your AccessKey ID.
        accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
        // Your AccessKey Secret.
        accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
        // The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole. You can set this by using the ALIBABA_CLOUD_ROLE_ARN environment variable.
        roleArn: '<RoleArn>',
        // A custom name for the role session. You can set this by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
        roleSessionName: '<RoleSessionName>',
        // Optional. An inline policy that limits the permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
        policy: '<Policy>',
        roleSessionExpiration: 3600,
    });
    const credentialClient = new Credential.default(credentialsConfig);
    const ecsConfig = new OpenApi.Config({
        endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The service endpoint.
        credential: credentialClient, // Specifies the credential to use.
    });
    const ecsClient = new Ecs20140526.default(ecsConfig);
    const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
    const runtime = new Util.RuntimeOptions();
    // Call the DescribeRegions operation.
    const response = ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime);
    console.log((await response).body.regions);
}
main().catch(console.error);
import Ecs20140526, * as $Ecs20140526 from '@alicloud/ecs20140526';
import Credential, { Config } from '@alicloud/credentials';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';
export default class Client {
    static async main(): Promise<$Ecs20140526.DescribeRegionsResponse> {
        const credentialsConfig = new Config({
            type: 'ram_role_arn',
            accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
            accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
            // The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole. You can set this by using the ALIBABA_CLOUD_ROLE_ARN environment variable.
            roleArn: '<RoleArn>',
            // A custom name for the role session. You can set this by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
            roleSessionName: '<RoleSessionName>',
            // Optional. An inline policy that limits the permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
            policy: '<Policy>',
            roleSessionExpiration: 3600,
        });
        const credentialClient = new Credential(credentialsConfig);
        let config = new $OpenApi.Config({
            credential: credentialClient, // Specifies the credential to use.
            endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The service endpoint.
        });
        let client = new Ecs20140526(config);
        let describeRegionsRequest = new $Ecs20140526.DescribeRegionsRequest({});
        let runtime = new $Util.RuntimeOptions({});
        return await client.describeRegionsWithOptions(describeRegionsRequest, runtime);
    }
}
const response = Client.main();
response.then(res => {
    console.log(res.body?.regions);
});

Method 5: ECS instance RAM role

Attach an instance RAM role to an ECS instance or elastic container instance. Applications on the instance can then use the Credentials tool to automatically obtain an STS token for the role.

By default, the Credentials tool accesses the ECS metadata server in security hardening mode (IMDSv2). If an error occurs, it falls back to normal mode. Control this behavior with the disableIMDSv1 parameter or the ALIBABA_CLOUD_IMDSV1_DISABLE environment variable:

  • false (default): Falls back to normal mode on failure.

  • true: Uses only security hardening mode and throws an exception on failure.

Support for IMDSv2 depends on your server's configuration.

You can also disable credential access through ECS metadata by setting the environment variable ALIBABA_CLOUD_ECS_METADATA_DISABLED=true.

Note
const Credential = require('@alicloud/credentials');
const credentialsConfig = new Credential.Config({
    type: 'ecs_ram_role',
    // Optional. The name of the ECS RAM role. If unspecified, the system retrieves it automatically. Specifying a name is recommended to reduce requests. This can also be set via the ALIBABA_CLOUD_ECS_METADATA environment variable.
    roleName: '<RoleName>',
    // Optional. Default: false. If true, enforces security hardening mode. If false, the system tries security hardening mode first, falling back to normal mode (IMDSv1) on failure.
    // disableIMDSv1: true,
});
const cred = new Credential.default(credentialsConfig);
import Credential, { Config } from '@alicloud/credentials';
const credentialsConfig = new Config({
    type: 'ecs_ram_role',
    // Optional. The name of the ECS RAM role. If unspecified, the system retrieves it automatically. Specifying a name is recommended to reduce requests. This can also be set via the ALIBABA_CLOUD_ECS_METADATA environment variable.
    roleName: '<RoleName>',
    // Optional. Default: false. If true, enforces security hardening mode. If false, the system tries security hardening mode first, falling back to normal mode (IMDSv1) on failure.
    // disableIMDSv1: true,
});
const credentialClient = new Credential(credentialsConfig);

API call

This example calls the DescribeRegions operation of ECS. To run the code, first install the ECS SDK.

const Ecs20140526 = require('@alicloud/ecs20140526');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Credential = require('@alicloud/credentials');
async function main() {
    const credentialsConfig = new Credential.Config({
        // The credential type.
        type: 'ecs_ram_role',
        // Optional. The name of the ECS RAM role. We recommend specifying this to reduce requests. If omitted, the system retrieves it automatically. You can also set the roleName parameter by using the ALIBABA_CLOUD_ECS_METADATA environment variable.
        roleName: '<RoleName>',
    });
    const credentialClient = new Credential.default(credentialsConfig);
    const ecsConfig = new OpenApi.Config({
        endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The service endpoint.
        credential: credentialClient, // The credential to use for authentication.
    });
    const ecsClient = new Ecs20140526.default(ecsConfig);
    const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
    const runtime = new Util.RuntimeOptions();
    // Call the DescribeRegions operation and obtain the response.
    const response = ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime);
    console.log((await response).body.regions);
}
main().catch(console.error);
import Ecs20140526, * as $Ecs20140526 from '@alicloud/ecs20140526';
import Credential, { Config } from '@alicloud/credentials';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';
export default class Client {
    static async main(): Promise<$Ecs20140526.DescribeRegionsResponse> {
        const credentialsConfig = new Config({
            type: 'ecs_ram_role',
            // Optional. The name of the ECS RAM role. We recommend specifying this to reduce requests. If omitted, the system retrieves it automatically. You can also set the roleName parameter by using the ALIBABA_CLOUD_ECS_METADATA environment variable.
            roleName: '<RoleName>',
            // Optional. Defaults to `false`. Setting this to `true` enforces security hardening mode. If this parameter is set to false, the system first attempts to get credentials in security hardening mode and falls back to normal mode (IMDSv1) if the attempt fails.
            // disableIMDSv1: true,
        });
        const credentialClient = new Credential(credentialsConfig);
        let config = new $OpenApi.Config({
            credential: credentialClient, // The credential to use for authentication.
            endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The service endpoint.
        });
        let client = new Ecs20140526(config);
        let describeRegionsRequest = new $Ecs20140526.DescribeRegionsRequest({});
        let runtime = new $Util.RuntimeOptions({});
        return await client.describeRegionsWithOptions(describeRegionsRequest, runtime);
    }
}
const response = Client.main();
response.then(res => {
    console.log(res.body?.regions);
});

Method 6: Use OIDCRoleArn

If you use OIDC and have created a RAM role for an OIDC provider, pass an OIDC provider ARN, an OIDC token, and a RAM role ARN to the Credentials SDK. The SDK calls the AssumeRoleWithOIDC operation to obtain an STS token. These credentials support automatic refresh. Auto-refresh mechanism for session credentials. For example, in an ACK cluster with RRSA enabled, the SDK reads OIDC configuration from Pod environment variables and obtains an STS token to access Alibaba Cloud services.

const Credential = require('@alicloud/credentials');
const credentialsConfig = new Credential.Config({
    type: 'oidc_role_arn',
    // The RAM role ARN to assume. You can also set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
    roleArn: '<RoleArn>',
    // The OIDC IdP ARN. You can also set this using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
    oidcProviderArn: '<OidcProviderArn>',
    // The OIDC token file path. You can also set this using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
    oidcTokenFilePath: '<OidcTokenFilePath>',
    // A custom role session name. You can also set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
    roleSessionName: '<RoleSessionName>',
    // Optional. A policy to scope down the permissions for the session. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    policy: '<Policy>',
    // The session duration in seconds.
    roleSessionExpiration: 3600,
});
const credentialClient = new Credential.default(credentialsConfig);
import Credential, { Config } from '@alicloud/credentials';
const credentialsConfig = new Config({
    type: 'oidc_role_arn',
    // The RAM role ARN to assume. You can also set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
    roleArn: '<RoleArn>',
    // The OIDC IdP ARN. You can also set this using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
    oidcProviderArn: '<OidcProviderArn>',
    // The OIDC token file path. You can also set this using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
    oidcTokenFilePath: '<OidcTokenFilePath>',
    // A custom role session name. You can also set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
    roleSessionName: '<RoleSessionName>',
    // Optional. A policy to scope down the permissions for the session. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    policy: '<Policy>',
    // The session duration in seconds.
    roleSessionExpiration: 3600,
});
const credentialClient = new Credential(credentialsConfig);

API call

This example shows how to call the DescribeRegions operation of ECS. To run the code, install the ECS SDK.

const Ecs20140526 = require('@alicloud/ecs20140526');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Credential = require('@alicloud/credentials');
async function main() {
    const credentialsConfig = new Credential.Config({
        // The credential type.
        type: 'oidc_role_arn',
        // The ARN of the RAM role to assume. You can also set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
        roleArn: '<RoleArn>',
        // The ARN of the OIDC provider. You can also set this using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
        oidcProviderArn: '<OidcProviderArn>',
        // The OIDC token file path. You can also set this using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
        oidcTokenFilePath: '<OidcTokenFilePath>',
        // A custom role session name. You can also set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
        roleSessionName: '<RoleSessionName>',
        // Optional. A policy that limits the permissions for the session. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
        policy: '<Policy>',
        // The session expiration in seconds.
        roleSessionExpiration: 3600,
    });
    const credentialClient = new Credential.default(credentialsConfig);
    const ecsConfig = new OpenApi.Config({
        endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The service endpoint.
        credential: credentialClient, // The authentication credential.
    });
    const ecsClient = new Ecs20140526.default(ecsConfig);
    const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
    const runtime = new Util.RuntimeOptions();
    // Call the DescribeRegions operation.
    const response = ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime);
    console.log((await response).body.regions);
}
main().catch(console.error);
import Ecs20140526, * as $Ecs20140526 from '@alicloud/ecs20140526';
import Credential, { Config } from '@alicloud/credentials';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';
export default class Client {
    static async main(): Promise<$Ecs20140526.DescribeRegionsResponse> {
        const credentialsConfig = new Config({
            type: 'oidc_role_arn',
            // The ARN of the RAM role to assume. You can also set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
            roleArn: '<RoleArn>',
            // The ARN of the OIDC provider. You can also set this using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
            oidcProviderArn: '<OidcProviderArn>',
            // The OIDC token file path. You can also set this using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
            oidcTokenFilePath: '<OidcTokenFilePath>',
            // A custom role session name. You can also set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
            roleSessionName: '<RoleSessionName>',
            // Optional. A policy that limits the permissions for the session. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
            policy: '<Policy>',
            // The session expiration in seconds.
            roleSessionExpiration: 3600,
        });
        const credentialClient = new Credential(credentialsConfig);
        let config = new $OpenApi.Config({
            credential: credentialClient, // The authentication credential.
            endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The service endpoint.
        });
        let client = new Ecs20140526(config);
        let describeRegionsRequest = new $Ecs20140526.DescribeRegionsRequest({});
        let runtime = new $Util.RuntimeOptions({});
        return await client.describeRegionsWithOptions(describeRegionsRequest, runtime);
    }
}
const response = Client.main();
response.then(res => {
    console.log(res.body?.regions);
});

Method 7: URI credential

Expose the STS service through a URI so external services can obtain an STS token without handling AccessKey pairs directly. The Credentials tool retrieves an STS token from the specified URI and uses it as an access credential, with automatic refresh support. Automatic refresh mechanism for session-type credentials.

const Credential = require('@alicloud/credentials');
const config = new Credential.Config({
    type: 'credentials_uri',
    // The endpoint to retrieve credentials, for example, http://local_or_remote_uri/. This can also be set with the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
    credentialsURI: '<CredentialsUri>',
});
const credentialClient = new Credential(config);
import Credential, { Config } from '@alicloud/credentials';
const credentialsConfig = new Config({
    type: 'credentials_uri',
    // The endpoint to retrieve credentials, for example, http://local_or_remote_uri/. This can also be set with the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
    credentialsURI: '<CredentialsUri>',
});
const credentialClient = new Credential(credentialsConfig);

The URI response must meet these requirements:

  • Status code is 200.

  • Response body format:

    {
      "Code": "Success",
      "AccessKeySecret": "AccessKeySecret",
      "AccessKeyId": "AccessKeyId",
      "Expiration": "2021-09-26T03:46:38Z",
      "SecurityToken": "SecurityToken"
    }

API call

This example demonstrates how to call the DescribeRegions operation of ECS. Before running the code, install the ECS SDK.

const Ecs20140526 = require('@alicloud/ecs20140526');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Credential = require('@alicloud/credentials');
async function main() {
    const credentialsConfig = new Credential.Config({
        // The credential type.
        type: 'credentials_uri',
        // The URI for obtaining the credential, formatted as http://local_or_remote_uri/. Alternatively, set the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
        credentialsURI: '<CredentialsUri>',
    });
    const credentialClient = new Credential.default(credentialsConfig);
    const ecsConfig = new OpenApi.Config({
        endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The service endpoint.
        credential: credentialClient, // The credential client for authentication.
    });
    const ecsClient = new Ecs20140526.default(ecsConfig);
    const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
    const runtime = new Util.RuntimeOptions();
    // Calls the DescribeRegions operation.
    const response = ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime);
    console.log((await response).body.regions);
}
main().catch(console.error);
import Ecs20140526, * as $Ecs20140526 from '@alicloud/ecs20140526';
import Credential, { Config } from '@alicloud/credentials';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';
export default class Client {
    static async main(): Promise<$Ecs20140526.DescribeRegionsResponse> {
        let credentialsConfig = new Config({
            type: 'credentials_uri',
            // The URI for obtaining the credential, formatted as http://local_or_remote_uri/. Alternatively, set the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
            credentialsURI: '<CredentialsUri>',
        });
        let credentialClient = new Credential(credentialsConfig);
        let config = new $OpenApi.Config({
            credential: credentialClient, // The credential client for authentication.
            endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The service endpoint.
        });
        let client = new Ecs20140526(config);
        let describeRegionsRequest = new $Ecs20140526.DescribeRegionsRequest({});
        let runtime = new $Util.RuntimeOptions({});
        return await client.describeRegionsWithOptions(describeRegionsRequest, runtime);
    }
}
const response = Client.main();
response.then(res => {
    console.log(res.body?.regions);
});

Method 8: Use a bearer token

Currently, only Alibaba Cloud Call Center (CCC) supports bearer token authentication.

const Credential = require('@alicloud/credentials');
const config = new Credential.Config({
    type: 'bearer',
    // Replace with your bearer token.
    bearerToken: '<BearerToken>',
});
const credentialClient = new Credential(config);
import Credential, { Config } from '@alicloud/credentials';
const credentialsConfig = new Config({
    type: 'bearer',
    // Replace with your bearer token.
    bearerToken: '<BearerToken>',
});
const credentialClient = new Credential(credentialsConfig);

API call

This example shows how to call the GetInstance operation of Cloud Call Center (CCC). To run the code, install the Cloud Call Center SDK.

const CCC20200701 = require('@alicloud/ccc20200701');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Credential = require('@alicloud/credentials');
async function main() {
    let credentialsConfig = new Credential.Config({
        // The credential type.
        type: 'bearer',
        // Specify your bearer token.
        bearerToken: '<BearerToken>',
    });
    let credentialClient = new Credential.default(credentialsConfig);
    let config = new OpenApi.Config({
        endpoint: 'ccc.cn-shanghai.aliyuncs.com',
        credential: credentialClient
    });
    let client = new CCC20200701.default(config);
    let getInstanceRequest = new CCC20200701.GetInstanceRequest({
        instanceId: 'ccc-test',
    });
    let runtime = new Util.RuntimeOptions({});
    let response = client.getInstanceWithOptions(getInstanceRequest, runtime);
    console.log((await response).body);
}
main().catch(console.error);
import ccc20200701, * as $ccc20200701 from '@alicloud/ccc20200701';
import Credential, { Config } from '@alicloud/credentials';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';
export default class Client {
    static async main(): Promise<$ccc20200701.GetInstanceResponse> {
        let credentialsConfig = new Config({
            type: 'bearer',
            // Specify your bearer token.
            bearerToken: '<BearerToken>',
        });
        let credentialClient = new Credential(credentialsConfig);
        let config = new $OpenApi.Config({
            credential: credentialClient, // Specify the credential.
            endpoint: 'ccc.cn-shanghai.aliyuncs.com', // Specify the endpoint.
        });
        let client = new ccc20200701(config);
        let GetInstanceRequest = new $ccc20200701.GetInstanceRequest({
            instanceId: 'ccc-test',
        });
        let runtime = new $Util.RuntimeOptions({});
        return await client.getInstanceWithOptions(GetInstanceRequest, runtime);
    }
}
let response = Client.main();
response.then(res => {
    console.log(res.body?.regions);
});

Default credential provider chain

The default credential provider chain lets you use the same code across environments and control credential retrieval through external configuration. When you call new Credential() without parameters, the SDK searches for credentials in the following order.

1. Using environment variables

If no credential is found in the system properties, the provider chain then checks for environment variables.

  • If both ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are present and not empty, the provider chain uses them as the default credential.

  • If ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and ALIBABA_CLOUD_SECURITY_TOKEN are also set, the provider chain uses an STS token as the default credential.

2. OIDC RAM roles

If no credential has been found, the provider chain checks for the following environment variables related to an OIDC RAM role:

  • ALIBABA_CLOUD_ROLE_ARN: The ARN of the RAM role.

  • ALIBABA_CLOUD_OIDC_PROVIDER_ARN: The ARN of the OIDC provider.

  • ALIBABA_CLOUD_OIDC_TOKEN_FILE: The file path of the OIDC token.

If all three environment variables are present and not empty, the provider chain uses these values to call the AssumeRoleWithOIDC API of the Security Token Service (STS) to obtain an STS token.

3. Config.json

If no credential has been found, the provider chain attempts to load the shared credentials file, config.json, from its default location and uses the credential specified in the file.

  • Linux/macOS: ~/.aliyun/config.json

  • Windows: C:\Users\USER_NAME\.aliyun\config.json

To configure a credential this way, you can use the Alibaba Cloud CLI or manually create a config.json file in the appropriate path. The following example shows the content format:

{
  "current": "<PROFILE_NAME>",
  "profiles": [
    {
      "name": "<PROFILE_NAME>",
      "mode": "AK",
      "access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
      "access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>"
    },
    {
      "name": "<PROFILE_NAME1>",
      "mode": "StsToken",
      "access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
      "access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
      "sts_token": "<SECURITY_TOKEN>"
    },
    {
      "name":"<PROFILE_NAME2>",
      "mode":"RamRoleArn",
      "access_key_id":"<ALIBABA_CLOUD_ACCESS_KEY_ID>",
      "access_key_secret":"<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
      "ram_role_arn":"<ROLE_ARN>",
      "ram_session_name":"<ROLE_SESSION_NAME>",
      "expired_seconds":3600
    },
    {
      "name":"<PROFILE_NAME3>",
      "mode":"EcsRamRole",
      "ram_role_name":"<RAM_ROLE_ARN>"
    },
    {
      "name":"<PROFILE_NAME4>",
      "mode":"OIDC",
      "oidc_provider_arn":"<OIDC_PROVIDER_ARN>",
      "oidc_token_file":"<OIDC_TOKEN_FILE>",
      "ram_role_arn":"<ROLE_ARN>",
      "ram_session_name":"<ROLE_SESSION_NAME>",
      "expired_seconds":3600
    },
    {
      "name":"<PROFILE_NAME5>",
      "mode":"ChainableRamRoleArn",
      "source_profile":"<PROFILE_NAME>",
      "ram_role_arn":"<ROLE_ARN>",
      "ram_session_name":"<ROLE_SESSION_NAME>",
      "expired_seconds":3600
    }
  ]
}

Parameter

Description

current

Specify the credential name to retrieve the corresponding credential configuration. The credential name is the value of the name parameter in profiles. By default, the system gives priority to the credential name specified by the ALIBABA_CLOUD_PROFILE environment variable. If this environment variable is not configured, the system uses the credential name specified by current.

profiles

Contains a collection of credential configurations. The mode parameter specifies the type of credential:

  • AK: Uses a RAM user's AccessKey as the credential.

  • StsToken: Uses an STS token as the credential.

  • RamRoleArn: Assumes a RAM role by using a RAM user's credentials to obtain a temporary credential.

  • EcsRamRole: Obtains a credential from instance metadata.

  • OIDC: Obtains a credential by using an OIDC provider ARN, an OIDC token, and a RAM role ARN.

  • ChainableRamRoleArn: Uses role chaining to obtain a new credential, using an initial credential from profiles that is specified by the source_profile parameter.

4. ECS instance RAM role

If no higher-priority credentials are found, the SDK retrieves credentials from the ECS instance RAM role. It accesses the instance metadata service in enhanced mode (IMDSv2) to get an STS token. This requires two requests: one for the role name, one for the credentials. To reduce this to one request, set the role name in the ALIBABA_CLOUD_ECS_METADATA environment variable. If enhanced mode fails, the process falls back to normal mode. Control this with ALIBABA_CLOUD_IMDSV1_DISABLE:

  1. false: Falls back to normal mode on failure.

  2. true: Uses only enhanced mode and throws an exception on failure.

IMDSv2 support depends on your instance metadata service configuration.

To disable credential retrieval from ECS instance metadata, set ALIBABA_CLOUD_ECS_METADATA_DISABLED=true.

Note

5. Credentials URI

If no credential has been found, the provider chain checks for the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. If this variable is set and points to a valid URI, the chain accesses the URI to retrieve an STS token.

Auto-refresh for session credentials

Session credentials (ram_role_arn, ecs_ram_role, oidc_role_arn, and credentials_uri) include built-in auto-refresh. On first retrieval, the credentials tool caches the credential. Subsequent requests return the cached value until it expires, at which point a new credential is fetched automatically.

Note

For ecs_ram_role credentials, the credentials tool proactively refreshes them 15 minutes before they expire.

The following example uses the singleton pattern to create a credential client, verifying auto-refresh by retrieving credentials at different intervals and confirming validity through an OpenAPI call.

const Credential = require('@alicloud/credentials');
const Ecs20140526 = require('@alicloud/ecs20140526');
const { Config } = require('@alicloud/openapi-client');
const { RuntimeOptions } = require('@alicloud/tea-util');
// Obtain environment variables.
const accessKeyId = process.env.ALIBABA_CLOUD_ACCESS_KEY_ID;
const accessKeySecret = process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET;
const roleArn = process.env.ALIBABA_CLOUD_ROLE_ARN;
/**
 * The Credential singleton class manages Alibaba Cloud credential instances.
 */
class CredentialClient {
    constructor() {
        if (!CredentialClient.instance) {
            var credentialsConfig = new Credential.Config({
                type: 'ram_role_arn',
                accessKeyId: accessKeyId,
                accessKeySecret: accessKeySecret,
                roleArn: roleArn,
                roleSessionName: 'RoleSessionNameTest',
                roleSessionExpiration: 3600,
            });
            this.credentialsClient = new Credential.default(credentialsConfig);
            CredentialClient.instance = this;
        }
        return CredentialClient.instance;
    }
    static getInstance() {
        return new CredentialClient().credentialsClient;
    }
}
/**
 * The ECS Client singleton class manages ECS client instances.
 */
class EcsClient {
    constructor(credentialClient) {
        if (!EcsClient.instance) {
            const config = new Config({
                endpoint: 'ecs.cn-hangzhou.aliyuncs.com',
                credential: credentialClient
            });
            this.ecsClient = new Ecs20140526.default(config);
            EcsClient.instance = this;
        }
        return EcsClient.instance;
    }
    static getInstance(credentialClient) {
        return new EcsClient(credentialClient).ecsClient;
    }
}
/**
 * Execute the task logic.
 */
async function executeTask() {
    try {
        const credentialClient = CredentialClient.getInstance();
        const credential = await credentialClient.getCredential();
        console.log(new Date());
        console.log(`AK ID: ${credential.accessKeyId}`);
        console.log(`AK Secret: ${credential.accessKeySecret}`);
        console.log(`STS Token: ${credential.securityToken}`);
        // This example calls an ECS API operation to verify the credential's validity. Modify this as needed.
        const ecsClient = EcsClient.getInstance(credentialClient);
        const request = new Ecs20140526.DescribeRegionsRequest();
        const runtime = new RuntimeOptions({});
        const response = await ecsClient.describeRegionsWithOptions(request, runtime);
        console.log(`Invoke result: ${response.statusCode}`);
    } catch (error) {
        throw new Error(`ECS client execution failed: ${error.message}`, { cause: error });
    }
}
/**
 * Schedule task execution by using a timer.
 */
function scheduleTasks() {
    // Immediately run the task once.
    executeTask();
    // Set a delay for subsequent tasks.
    setTimeout(executeTask, 600 * 1000); // Second run: after 600 seconds.
    setTimeout(executeTask, 4200 * 1000); // Third run: after 4,200 seconds.
    setTimeout(executeTask, 4300 * 1000); // Fourth run: after 4,300 seconds.
}
// Start task scheduling.
scheduleTasks();
import Credential, { Config as CredentialsConfig }  from '@alicloud/credentials';
import Ecs20140526, * as $Ecs20140526 from '@alicloud/ecs20140526';
import { Config } from '@alicloud/openapi-client';
import { RuntimeOptions } from '@alicloud/tea-util';
// Obtain environment variables.
const accessKeyId: string | undefined = process.env.ALIBABA_CLOUD_ACCESS_KEY_ID;
const accessKeySecret: string | undefined = process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET;
const roleArn: string | undefined = process.env.ALIBABA_CLOUD_ROLE_ARN;
if (!accessKeyId || !accessKeySecret || !roleArn) {
    throw new Error('Missing required environment variables.');
}
/**
 * The Credential singleton class manages Alibaba Cloud credential instances.
 */
class CredentialClient {
    private static instance: CredentialClient;
    private readonly credentialsClient: InstanceType<typeof Credential>;
    private constructor() {
        const credentialsConfig = new CredentialsConfig({
            type: 'ram_role_arn',
            accessKeyId,
            accessKeySecret,
            roleArn,
            roleSessionName: 'RoleSessionNameTest',
            roleSessionExpiration: 3600,
        });
        this.credentialsClient = new Credential(credentialsConfig);
    }
    static getInstance(): InstanceType<typeof Credential> {
        if (!CredentialClient.instance) {
            CredentialClient.instance = new CredentialClient();
        }
        return CredentialClient.instance.credentialsClient;
    }
}
/**
 * The ECS Client singleton class manages ECS client instances.
 */
class EcsClient {
    private static instance: EcsClient;
    private readonly ecsClient: InstanceType<typeof Ecs20140526>;
    private constructor(credentialClient: InstanceType<typeof Credential>) {
        const config = new Config({
            endpoint: 'ecs.cn-hangzhou.aliyuncs.com',
            credential: credentialClient
        });
        this.ecsClient = new Ecs20140526(config);
    }
    static getInstance(credentialClient: InstanceType<typeof Credential>): InstanceType<typeof Ecs20140526> {
        if (!EcsClient.instance) {
            EcsClient.instance = new EcsClient(credentialClient);
        }
        return EcsClient.instance.ecsClient;
    }
}
/**
 * Execute the task logic.
 */
async function executeTask(): Promise<void> {
    try {
        const credentialClient = CredentialClient.getInstance();
        const credential = await credentialClient.getCredential();
        console.log(new Date());
        console.log(`AK ID: ${credential.accessKeyId}`);
        console.log(`AK Secret: ${credential.accessKeySecret}`);
        console.log(`STS Token: ${credential.securityToken}`);
        // This example calls an ECS API operation to verify the credential's validity. Modify this as needed.
        const ecsClient = EcsClient.getInstance(credentialClient);
        const request = new $Ecs20140526.DescribeRegionsRequest();
        const runtime = new RuntimeOptions({});
        const response = await ecsClient.describeRegionsWithOptions(request, runtime);
        console.log(`Invoke result: ${response.statusCode}`);
    } catch (error) {
        throw new Error(`ECS client execution failed: ${error}`);
    }
}
/**
 * Schedule task execution by using a timer.
 */
function scheduleTasks(): void {
    // Immediately run the task once.
    executeTask();
    // Set a delay for subsequent tasks.
    setTimeout(executeTask, 600 * 1000); // Second run: after 600 seconds.
    setTimeout(executeTask, 4200 * 1000); // Third run: after 4,200 seconds.
    setTimeout(executeTask, 4300 * 1000); // Fourth run: after 4,300 seconds.
}
// Start task scheduling.
scheduleTasks();
2025-05-28T09:22:29.584Z
AK ID: STS.NVS9xxx7DRbao
AK Secret: 9SoQxxxmVjVsED9ad47rcgMaw5XyQyXx
STS Token:
CAISyQJ1q6Ft5B2yfSjIr5Xmcu/irrxq0pWvU0PZhvVtS7hovafKjTz2IHhMeXZoA+4YsPw2mmFW6/sdlrpJTJtIfkHfdsp36LJe9A6dbpHd4xc1LGed0s/LI3OaLjKm9u2wCryLYbGwU/OpbE++5U0X6LDmdDKkckW40JmS8/BOZcgWWQ/KB1gvRq
0hRG1YpdQdKGHa0xxxWg0/ks0aH1war1bBL+tqofMP9MfMBZskvD42Hu8VtbbfE3SJq7BxHybx71qQs+02c5onAXAELvUvYa7OKo4MyCVBjBKEhALNBoeL7kfBobmFAAkgwYnynVMMisES3LOiIqKOsk1MdI9Cywly2y
vfiZZ1prmk1pV68xxxczc4yvhD2nuNe7rmc9Z3/JHusVmo7LiTxqAARdkoKCeYBvLk0ZFWccCiM0ZvdnRtv0VDOUfD1zQELQGL+xB5NrBmdzq2ePjFJbrkBGmy5EXD714jknyzM4lFic2dUQMi14NCHMVDVjGAf0qUs
F+PQW58jGb32fmFxxxTXOx82sdRQqW0/vTd2KQmIAA=
Invoke result: 200
2025-05-28T09:32:28.137Z
AK ID: STS.NVS9xxx7DRbao
AK Secret: 9SoQxxxmVjVsED9ad47rcgMaw5XyQyXx
STS Token:
CAISyQJ1q6Ft5B2yfSjIr5Xmcu/irrxq0pWvU0PZhvVtS7hovafKjTz2IHhMeXZoA+4YsPw2mmFW6/sdlrpJTJtIfkHfdsp36LJe9A6dbpHd4xc1LGed0s/LI3OaLjKm9u2wCryLYbGwU/OpbE++5U0X6LDmdDKkckW40JmS8/BOZcgWWQ/KB1gvRq
0hRG1YpdQdKGHa0xxxWg0/ks0aH1war1bBL+tqofMP9MfMBZskvD42Hu8VtbbfE3SJq7BxHybx71qQs+02c5onAXAELvUvYa7OKo4MyCVBjBKEhALNBoeL7kfBobmFAAkgwYnynVMMisES3LOiIqKOsk1MdI9Cywly2y
vfiZZ1prmk1pV68xxxczc4yvhD2nuNe7rmc9Z3/JHusVmo7LiTxqAARdkoKCeYBvLk0ZFWccCiM0ZvdnRtv0VDOUfD1zQELQGL+xB5NrBmdzq2ePjFJbrkBGmy5EXD714jknyzM4lFic2dUQMi14NCHMVDVjGAf0qUs
F+PQW58jGb32fmFxxxTXOx82sdRQqW0/vTd2KQmIAA=
Invoke result: 200
2025-05-28T10:32:29.771Z
AK ID: STS.NVuaxxxLFiPw8
AK Secret: 5dsoxxxpA5pCzfrek4KforS8MnJ6qHR9
STS Token:
CAISyQJ1q6Ft5B2yfSjIr5XAKsjd241w4PqgY1P2gDUvb8NqhpXc2jz2IHhMeXZoA+4YsPw2mmFW6/sdlrpJTJtIfkHfdsp36LJe9A6dbpHd4yVKL2Gd0s/LI3OaLjKm9u2wCryLYbGwU/OpbE++5U0X6LDmdDKkckW40JmS8/BOZcgWWQ/KB1gvRq
0hRG1YpdQdKGHa0xxxWg0/ks0aH1war1bBL+tqofMP9MfMBZskvD42Hu8VtbbfE3SJq7BxHybx71qQs+02c5onAXAELvUvYa7OKo4MyCVBjBKEhALNBoeL7kfBobmFAAkgwYnynVMMisES3LOjIqKOsk+Mdk9CiWv2y
vfiZZ1prmk1pV68xxxczc4yvhD2nuNe7rmc9Z3/KpUoQEo7LiTxqAAUyV7F+kpLHRG/yHw3JaVz14hqSj2hmxxkwgczUWIkpBLKHLeW0iI3sp2LNQO6iEAImLpSE0nRVBbcutIqxEuFzAs607jgOjHakTF7UZNoKVV
wb42xR4s4ThGd2PxxxqoUsrKfCq5lHiUiDq6L1VIAA=
Invoke result: 200
2025-05-28T10:34:08.130Z
AK ID: STS.NVuaxxxLFiPw8
AK Secret: 5dsoxxxpA5pCzfrek4KforS8MnJ6qHR9
STS Token:
CAISyQJ1q6Ft5B2yfSjIr5XAKsjd241w4PqgY1P2gDUvb8NqhpXc2jz2IHhMeXZoA+4YsPw2mmFW6/sdlrpJTJtIfkHfdsp36LJe9A6dbpHd4yVKL2Gd0s/LI3OaLjKm9u2wCryLYbGwU/OpbE++5U0X6LDmdDKkckW40JmS8/BOZcgWWQ/KB1gvRq
0hRG1YpdQdKGHa0xxxWg0/ks0aH1war1bBL+tqofMP9MfMBZskvD42Hu8VtbbfE3SJq7BxHybx71qQs+02c5onAXAELvUvYa7OKo4MyCVBjBKEhALNBoeL7kfBobmFAAkgwYnynVMMisES3LOjIqKOsk+Mdk9CiWv2y
vfiZZ1prmk1pV68xxxczc4yvhD2nuNe7rmc9Z3/KpUoQEo7LiTxqAAUyV7F+kpLHRG/yHw3JaVz14hqSj2hmxxkwgczUWIkpBLKHLeW0iI3sp2LNQO6iEAImLpSE0nRVBbcutIqxEuFzAs607jgOjHakTF7UZNoKVV
wb42xR4s4ThGd2PxxxqoUsrKfCq5lHiUiDq6L1VIAA=
Invoke result: 200

Analysis based on the log output:

  • On the first call, the cache is empty. The system retrieves a credential based on your configuration and then stores it in the cache.

  • The second call uses the same credential as the first, indicating it was retrieved from the cache.

  • On the third call, the cached credential has expired. Its expiration time (RoleSessionExpiration) is 3,600 seconds, but this call is made 4,200 seconds after the first one. Consequently, the SDK's automatic refresh mechanism fetches a new credential and updates the cache.

  • The fourth call uses the same credential as the third, confirming that the cache was updated.

Related documents