Manage access credentials
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:
-
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.
-
An STS token provides temporary credentials for a RAM role with a configurable validity period and permission scope. What is STS.
-
A bearer token is used for authentication and authorization.
Prerequisites
-
Node.js 8.5.0 or later is installed.
-
Alibaba Cloud SDK V2.0 is configured. Use the Alibaba Cloud SDK for Node.js with an IDE.
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.
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 |
× |
× |
- |
× |
- |
× |
× |
|
roleName: The name of the RAM role. |
× |
× |
× |
- |
× |
× |
× |
|
disableIMDSv1: Specifies whether to enforce the security hardening mode (IMDSv2). Default value: |
× |
× |
× |
- |
× |
× |
× |
|
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: |
× |
× |
- |
× |
- |
× |
× |
|
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.
-
Never store an
AccessKeyin 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 patternfor thecredentials tool. This enables the built-incredential cache, preventingrate limitingfrom 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
Method 2: Use an AccessKey
The Credentials tool uses the AccessKey you provide as the access credential.
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
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
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
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.
-
Security hardening mode requires credentials library version 2.3.1 or later.
-
ECS instance metadata overview: Instance metadata.
-
To grant a RAM role to an ECS or elastic container instance: Step 1: Create a RAM role and Grant an instance RAM role to an ECI instance.
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
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
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
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
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 |
|
profiles |
Contains a collection of credential configurations. The
|
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:
-
false: Falls back to normal mode on failure. -
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.
-
ECS instance metadata overview: Instance Metadata.
-
To grant a RAM role to an ECS or ECI instance: Step 1: Create a RAM role and Grant an instance RAM role to an ECI instance.
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.
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
-
For an overview of the basic concepts of RAM, see Basic concepts.
-
To create an AccessKey, see Create an AccessKey.
-
To programmatically create RAM users, AccessKeys, and RAM roles; define permission policies; and grant permissions, see RAM SDK overview.
-
To programmatically assume a role, see STS SDK overview.
-
For details about the RAM and STS APIs, see the API reference.
-
Best practices for using access credentials to call Alibaba Cloud OpenAPI