All Products
Search
Document Center

Alibaba Cloud SDK:Manage access credentials

最終更新日:Nov 22, 2024

When you call API operations to manage cloud resources by using Alibaba Cloud SDKs, you must configure valid credential information. The Alibaba Cloud Credentials tool provides powerful features that allow you to obtain and manage access credentials with ease. This topic describes how to use the Credentials tool to configure various types of credentials such as the default credential, AccessKey pairs, or Security Token Service (STS) tokens. This topic also describes the order based on which the Credentials tool obtains the default credential. You can develop a thorough knowledge of configuring and managing credentials in Alibaba Cloud SDKs. This ensures that you can perform operations on cloud resources in an efficient and secure manner.

Background information

A credential is a set of information that is used to prove the identity of a user. When you log on to the system, you must use a valid credential to complete identity authentication. The following types of credentials are commonly used:

  1. An AccessKey pair of an Alibaba Cloud account or a Resource Access Management (RAM) user. An AccessKey pair is permanently valid and consists of an AccessKey ID and an AccessKey secret.

  2. An STS token of a RAM role. An STS token is a temporary credential. You can specify a validity period and access permissions for an STS token. For more information, see What is STS?

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

Prerequisites

Install the Credentials tool

Run the following npm command to download and install Alibaba Cloud Credentials for Node.js:

npm install @alicloud/credentials

We recommend that you use the latest version of Alibaba Cloud Credentials for Node.js. This ensures that all credentials are supported.

Initialize a Credentials client

You can use one of the following methods to initialize a Credentials client based on your business requirements:

Important
  • If you use a plaintext AccessKey pair in a project, the AccessKey pair may be leaked due to improper permission management on the code repository. This may threaten the security of all resources within the account to which the AccessKey pair belongs. We recommend that you store the AccessKey pair in environment variables or configuration files.

  • JavaScript is used in the following sample code.

Method 1: Use the default credential provider chain

If you do not specify a method to initialize a Credentials client, the default credential provider chain is used. For more information, see the Default credential provider chain section of this topic.

const Credential = require('@alicloud/credentials');

// Do not specify a method to initialize a Credentials client.
const credentialClient = new Credential.default();

Call example

The following sample code provides an example on how to call the DescribeRegions operation of Elastic Compute Service (ECS). Before you call this operation, you must install ECS SDK for Node.js.

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() {
  // Use the default credential to initialize a Credentials client. 
  const credentialClient = new Credential.default();
  const ecsConfig = new OpenApi.Config();
  // Specify the endpoint of ECS. 
  ecsConfig.endpoint = 'ecs.cn-hangzhou.aliyuncs.com';
  // Use the SDK Credentials package to configure a credential. 
  ecsConfig.credential = credentialClient;
  // Initialize the ECS SDK client.
  const ecsClient = new Ecs20140526.default(ecsConfig);
  // Initialize the request to call the DescribeRegions operation. 
  const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
  // Initialize the runtime configurations. 
  const runtime = new Util.RuntimeOptions();
  // Call the DescribeRegions operation and obtain a response. 
  ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime).then((result) => {
    console.log(JSON.stringify(result.body));
  });
}

main().catch(console.error);

Method 2: Use an AccessKey pair

You can create an AccessKey pair that is used to call API operations for your Alibaba Cloud account or a RAM user. For more information, see Create an AccessKey pair. Then, you can use the AccessKey pair to initialize a Credentials client.

Warning

An Alibaba Cloud account has full permissions on resources within the account. AccessKey pair leaks of an Alibaba Cloud account pose critical threats to the system.

Therefore, we recommend that you use an AccessKey pair of a RAM user that is granted permissions based on the principle of least privilege to initialize a Credentials client.

const Credential = require('@alicloud/credentials');

// Use an AccessKey pair to initialize a Credentials client. 
const credentialsConfig = new Credential.Config({
  // Specify the type of the credential. 
  type: 'access_key',
  // Specify the AccessKey ID. 
  accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
  // Specify the AccessKey secret. 
  accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
});
const credentialClient = new Credential.default(credentialsConfig);

Call example

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for Node.js.

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() {
  // Use an AccessKey pair to initialize a Credentials client. 
  const credentialsConfig = new Credential.Config({
    // Specify the type of the credential. 
    type: 'access_key',
    // Specify the AccessKey ID. 
    accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
    // Specify the AccessKey secret. 
    accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
  });
  const credentialClient = new Credential.default(credentialsConfig);

  const ecsConfig = new OpenApi.Config();
  // Specify the endpoint of ECS. 
  ecsConfig.endpoint = 'ecs.cn-hangzhou.aliyuncs.com';
  // Use the SDK Credentials package to configure a credential. 
  ecsConfig.credential = credentialClient;
  // Initialize the ECS SDK client.
  const ecsClient = new Ecs20140526.default(ecsConfig);
  // Initialize the request to call the DescribeRegions operation. 
  const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
  // Initialize the runtime configurations. 
  const runtime = new Util.RuntimeOptions();
  // Call the DescribeRegions operation and obtain a response. 
  ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime).then((response) => {
    console.log(response.body.regions);
  });
}

main().catch(console.error);

Method 3: Use an STS token

You can call the AssumeRole operation of STS as a RAM user to obtain an STS token. You can specify the maximum validity period of the STS token. The following example shows how to initialize a Credentials client by using an STS token. The example does not show how to obtain an STS token.

const Credential = require('@alicloud/credentials');

const credentialsConfig = new Credential.Config({
  type: 'sts',
  // Obtain the AccessKey ID from the environment variable.
  accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
  // Obtain the AccessKey secret from the environment variable.
  accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
  // Obtain the STS token from the environment variable.
  securityToken: process.env.ALIBABA_CLOUD_SECURITY_TOKEN,
});
const cred = new Credential.default(credentialsConfig);

Call example

You can use the Credentials tool to read an STS token and call the API operations of Alibaba Cloud services.

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for Node.js and STS SDK for Node.js.

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 main() {
  // Create an STS client and call the AssumeRole operation to obtain the STS token.
  const stsConfig = new OpenApi.Config();
  stsConfig.endpoint = 'sts.cn-hangzhou.aliyuncs.com';
  // Obtain the AccessKey ID from the environment variable.
  stsConfig.accessKeyId = process.env.ALIBABA_CLOUD_ACCESS_KEY_ID;
  // Obtain the AccessKey secret from the environment variable.
  stsConfig.accessKeySecret = process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET;
  const stsClient = new Sts20150401.default(stsConfig);
  const assumeRoleRequest = Sts20150401.AssumeRoleRequest;
  // Specify the validity period of the STS token.
  assumeRoleRequest.durationSeconds = 3600;
  // Specify the Alibaba Cloud Resource Name (ARN) of the Resource Access Management (RAM) role that you want to assume by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole.
  assumeRoleRequest.roleArn = '<RoleArn>';
  // Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
  assumeRoleRequest.roleSessionName = '<RoleSessionName>';
  // Specify the policies that you want to attach to the RAM role.
  // assumeRoleRequest.policy = "";
  const assumeRoleResponsePromise = stsClient.assumeRole(assumeRoleRequest);
  const assumeRoleResponseBodyCredentials = (await assumeRoleResponsePromise).body.credentials;

  // Use an STS token to initialize a Credentials client. 
  const credentialsConfig = new Credential.Config({
    // Specify the type of the credential. 
    type: 'sts',
    accessKeyId: assumeRoleResponseBodyCredentials.accessKeyId,
    accessKeySecret: assumeRoleResponseBodyCredentials.accessKeySecret,
    securityToken: assumeRoleResponseBodyCredentials.securityToken,
  });
  const credentialClient = new Credential.default(credentialsConfig);

  const ecsConfig = new OpenApi.Config();
  // Specify the endpoint of ECS. 
  ecsConfig.endpoint = 'ecs.cn-hangzhou.aliyuncs.com';
  // Use the SDK Credentials package to configure a credential. 
  ecsConfig.credential = credentialClient;
  // Initialize the ECS SDK client.
  const ecsClient = new Ecs20140526.default(ecsConfig);
  // Initialize the request to call the DescribeRegions operation. 
  const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
  // Initialize the runtime configurations. 
  const runtime = new Util.RuntimeOptions();
  // Call the DescribeRegions operation and obtain a response. 
  ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime).then((response) => {
    console.log(response.body.regions);
  });
}

main().catch(console.error);

Method 4: Use an AccessKey pair and a RAM role

The underlying logic of this method is to use an STS token to initialize a Credentials client. After you specify the ARN of a RAM role, the Credentials tool can obtain an STS token from STS. You can also use the policy parameter to limit the permissions of the RAM role.

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,
  // Specify the ARN of the RAM role that you want to assume by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole.
  roleArn: '<RoleArn>',
  // Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
  roleSessionName: '<RoleSessionName>',
  // Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}.
  policy: '<Policy>',
  roleSessionExpiration: 3600,
});
const cred = new Credential.default(credentialsConfig);

Call example

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for Node.js.

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() {
  // Use an AccessKey pair and a RAM role to initialize a Credentials client. 
  const credentialsConfig = new Credential.Config({
    // Specify the type of the credential. 
    type: 'ram_role_arn',
    // Specify the AccessKey ID. 
    accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
    // Specify the AccessKey secret. 
    accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
    // Specify the ARN of the RAM role that you want to assume by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole.
    roleArn: '<RoleArn>',
    // Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
    roleSessionName: '<RoleSessionName>',
    // Optional. Specify limited 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();
  // Specify the endpoint of ECS. 
  ecsConfig.endpoint = 'ecs.cn-hangzhou.aliyuncs.com';
  // Use the SDK Credentials package to configure a credential. 
  ecsConfig.credential = credentialClient;
  // Initialize the ECS SDK client.
  const ecsClient = new Ecs20140526.default(ecsConfig);
  // Initialize the request to call the DescribeRegions operation. 
  const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
  // Initialize the runtime configurations. 
  const runtime = new Util.RuntimeOptions();
  // Call the DescribeRegions operation and obtain a response. 
  const response = ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime);
  console.log((await response).body.regions);
}

main().catch(console.error);

Method 5: Use the RAM role of an ECS instance

You can attach a RAM role to an ECS instance or elastic container instance. The Credentials tool automatically obtains the RAM role attached to the instance and uses the metadata server to obtain the STS token of the RAM role. The STS token is then used to initialize a Credentials client.

The metadata server supports access in normal mode (IMDSv1) and security hardening mode (IMDSv2). By default, the Credentials tool obtains access credentials from the metadata server in security hardening mode. If an exception occurs in the security hardening mode, you can configure the DisableIMDSv1 parameter to specify an exception handling logic. Valid values of the DisableIMDSv1 parameter:

  1. false (default): The Credentials tool continues to obtain the access credential in normal mode.

  2. true: The exception is thrown and the Credentials tool continues to obtain the access credential in security hardening mode.

The configurations for the metadata server determine whether the server supports the security hardening mode.

Note
  • For more information about instance metadata, see Obtain instance metadata.

  • For more information about how to attach a RAM role to an ECS instance, see the "Create an instance RAM role and attach the instance RAM role to an ECS instance" section of the Instance RAM roles topic. For more information about how to attach a RAM role to an elastic container instance, see the "Assign the instance RAM role to an elastic container instance" section of the Use an instance RAM role by calling API operations topic.

const Credential = require('@alicloud/credentials');

const credentialsConfig = new Credential.Config({
  type: 'ecs_ram_role',
  // Optional. Specify the name of the RAM role of the ECS instance by specifying the ALIBABA_CLOUD_ECS_METADATA environment variable. If you do not specify this parameter, its value is automatically obtained. To reduce the number of requests, we recommend that you specify this parameter.
  roleName: '<RoleName>',
  // Set the DisableIMDSv1 parameter to true, which indicates that the security hardening mode is forcibly used. The default value is false, which indicates that the system first tries to obtain the access credential in security hardening mode. If the access credential fails to be obtained, the normal mode is used. 
  // disableIMDSv1: true,
});
const cred = new Credential.default(credentialsConfig);   

Call example

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() {
  // Use the RAM role of an ECS instance to initialize a Credentials client. 
  const credentialsConfig = new Credential.Config({
    // Specify the type of the credential. 
    type: 'ecs_ram_role',
    // Optional. Specify the name of the RAM role of the ECS instance by specifying the ALIBABA_CLOUD_ECS_METADATA environment variable. If you do not specify this parameter, its value is automatically obtained. To reduce the number of requests, we recommend that you specify this parameter.
    roleName: '<RoleName>',
  });
  const credentialClient = new Credential.default(credentialsConfig);

  const ecsConfig = new OpenApi.Config();
  // Specify the endpoint of ECS. 
  ecsConfig.endpoint = 'ecs.aliyuncs.com';
  // Use the SDK Credentials package to configure a credential. 
  ecsConfig.credential = credentialClient;
  // Initialize the ECS SDK client.
  const ecsClient = new Ecs20140526.default(ecsConfig);
  // Initialize the request to call the DescribeRegions operation. 
  const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
  // Initialize the runtime configurations. 
  const runtime = new Util.RuntimeOptions();
  // Call the DescribeRegions operation and obtain a response. 
  const response = ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime);
  console.log((await response).body.regions);
}

main().catch(console.error);

Method 6: Use the RAM role of an OIDC IdP

After you attach a RAM role to a worker node in a Container Service for Kubernetes cluster, applications in the pods on the worker node can use the metadata server to obtain an STS token in the same way as the applications on ECS instances. However, if an untrusted application is deployed on the worker node, such as an application that is submitted by your customer and whose code is unavailable to you, you may not want the application to use the metadata server to obtain an STS token of the RAM role attached to the worker node. To ensure the security of cloud resources and enable untrusted applications to securely obtain required STS tokens, you can use the RAM Roles for Service Accounts (RRSA) feature to grant minimum necessary permissions to an application. In this case, the ACK cluster creates a service account OpenID Connect (OIDC) token file, associates the token file with a pod, and then injects relevant environment variables into the pod. Then, the Credentials tool uses the environment variables to call the AssumeRoleWithOIDC operation of STS to obtain an STS token of the RAM role. For more information about the RRSA feature, see Use RRSA to authorize different pods to access different cloud services.

The following environment variables are injected into the pod:

ALIBABA_CLOUD_ROLE_ARN: the ARN of the RAM role.

ALIBABA_CLOUD_OIDC_PROVIDER_ARN: the ARN of the OIDC identity provider (IdP).

ALIBABA_CLOUD_OIDC_TOKEN_FILE: the path of the OIDC token file.

const Credential = require('@alicloud/credentials');

const credentialsConfig = new Credential.Config({
  type: 'oidc_role_arn',
  // Specify the ARN of the RAM role that you want to assume by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable.
  roleArn: '<RoleArn>',
  // Specify the ARN of the OIDC IdP by specifying the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
  oidcProviderArn: '<OidcProviderArn>',
  // Specify the path of the OIDC token file by specifying the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
  oidcTokenFilePath: '<OidcTokenFilePath>',
  // Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
  roleSessionName: '<RoleSessionName>',
  // Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}.
  policy: '<Policy>',
  // Specify the validity period of the session.
  roleSessionExpiration: 3600,
});
const credentialClient = new Credential.default(credentialsConfig);

Call example

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for Node.js.

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({
    // Specify the type of the credential. 
    type: 'oidc_role_arn',
    // Specify the ARN of the RAM role that you want to assume by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable.
    roleArn: '<RoleArn>',
    // Specify the ARN of the OIDC IdP by specifying the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
    oidcProviderArn: '<OidcProviderArn>',
    // Specify the path of the OIDC token file by specifying the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
    oidcTokenFilePath: '<OidcTokenFilePath>',
    // Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
    roleSessionName: '<RoleSessionName>',
    // Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}.
    policy: '<Policy>',
    // Specify the validity period of the session.
    roleSessionExpiration: 3600,
  });
  const credentialClient = new Credential.default(credentialsConfig);

  const ecsConfig = new OpenApi.Config();
  // Specify the endpoint of ECS. 
  ecsConfig.endpoint = 'ecs.aliyuncs.com';
  // Use the SDK Credentials package to configure a credential. 
  ecsConfig.credential = credentialClient;
  // Initialize the ECS SDK client.
  const ecsClient = new Ecs20140526.default(ecsConfig);
  // Initialize the request to call the DescribeRegions operation. 
  const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
  // Initialize the runtime configurations. 
  const runtime = new Util.RuntimeOptions();
  // Call the DescribeRegions operation and obtain a response. 
  const response = ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime);
  console.log((await response).body.regions);
}

main().catch(console.error);

Method 7: Use a credential URI

The underlying logic of this method is to use an STS token to initialize a Credentials client. The Credentials tool uses the uniform resource identifier (URI) that you provide to obtain an STS token. The STS token is then used to initialize a Credentials client.

const Credential = require('@alicloud/credentials');

const config = new Credential.Config({
  type: 'credentials_uri',
  // Specify the URI of the credential in the http://local_or_remote_uri/ format by specifying the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
  credentialsURI: '<CredentialsUri>',
});
const credentialClient = new Credential(config);

The URI must meet the following requirements:

  • The status code 200 is returned.

  • The following response parameters are returned:

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

Call example

To call the API operations of Alibaba Cloud services, you can specify a local or remote URI for credentials and use the Credentials tool to obtain and automatically update an STS token based on the local or remote URI.

To call the operations of an Alibaba Cloud service, you must install dependencies for the Alibaba Cloud service. The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for Node.js.

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() {
  // Use a credential URI to initialize a Credentials client. 
  const credentialsConfig = new Credential.Config({
    // Specify the type of the credential. 
    type: 'credentials_uri',
    // Specify the URI of the credential in the http://local_or_remote_uri/ format by specifying the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
    credentialsURI: '<CredentialsUri>',
  });
  const credentialClient = new Credential.default(credentialsConfig);

  const ecsConfig = new OpenApi.Config();
  // Specify the endpoint of ECS. 
  ecsConfig.endpointType = 'ecs.aliyuncs.com';
  // Use the SDK Credentials package to configure a credential. 
  ecsConfig.credential = credentialClient;
  // Initialize the ECS SDK client.
  const ecsClient = new Ecs20140526.default(ecsConfig);
  // Initialize the request to call the DescribeRegions operation. 
  const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
  // Initialize the runtime configurations. 
  const runtime = new Util.RuntimeOptions();
  // Call the DescribeRegions operation and obtain a response. 
  const response = ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime);
  console.log((await response).body.regions);
}

main().catch(console.error);

Method 8: Use a bearer token

Only Cloud Call Center allows you to use a bearer token to initialize a Credentials client.

const Credential = require('@alicloud/credentials');

const config = new Credential.Config({
  type: 'bearer',
  // Specify the bearer token.
  bearerToken: '<BearerToken>',
});
const credentialClient = new Credential(config);

Call example

The following sample code provides an example on how to call the GetInstance operation of Cloud Call Center. Before you call this operation, you must install Cloud Call Center SDK for Node.js.

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() {
  // Use a bearer token to initialize a Credentials client. 
  const credentialsConfig = new Credential.Config({
    // Specify the type of the credential. 
    type: 'bearer',
    // Specify the bearer token.
    bearerToken: '<BearerToken>',
  });
  const credentialClient = new Credential.default(credentialsConfig);

  let config = new OpenApi.Config();
  config.endpoint = `ccc.cn-shanghai.aliyuncs.com`;
  config.credential = credentialClient;

  const client = new CCC20200701.default(config);
  let getInstanceRequest = new CCC20200701.GetInstanceRequest({
    instanceId: 'ccc-test',
  });
  let runtime = new Util.RuntimeOptions({});
  const response = client.getInstanceWithOptions(getInstanceRequest, runtime);
  console.log((await response).body);
}

main().catch(console.error);

Default credential provider chain

If you want to use different types of credentials in the development and production environments of your application, you generally need to obtain the environment information from the code and write code branches to obtain different credentials for the development and production environments. The default credential provider chain of the Credentials tool allows you to use the same code to obtain credentials for different environments based on configurations independent of the application. If you use new Credential() to initialize a Credentials client without specifying an initialization method, the Credentials tool obtains the credential information in the following order:

1. Obtain the credential information from environment variables

If no credentials are found in the previous step, the Credentials tool obtains the credential information from environment variables.

  • If the ALIBABA_CLOUD_ACCESS_KEY_ID (AccessKey ID) and ALIBABA_CLOUD_ACCESS_KEY_SECRET (AccessKey secret) system environment variables are specified, the Credentials tool uses the specified AccessKey pair as the default credential.

  • If the ALIBABA_CLOUD_ACCESS_KEY_ID (AccessKey ID), ALIBABA_CLOUD_ACCESS_KEY_SECRET (AccessKey secret), and ALIBABA_CLOUD_SECURITY_TOKEN (STS token) system environment variables are specified, the Credentials tool uses the specified STS token as the default credential.

2. Obtain the credential information by using the RAM role of an OIDC IdP

If no credentials are found in the previous step, the Credentials tool obtains the values of the following environment variables:

ALIBABA_CLOUD_ROLE_ARN: the ARN of the RAM role.

ALIBABA_CLOUD_OIDC_PROVIDER_ARN: the ARN of the OIDC IdP.

ALIBABA_CLOUD_OIDC_TOKEN_FILE: the path of the OIDC token file.

If the preceding three environment variables are specified, the Credentials tool uses the environment variables to call the AssumeRoleWithOIDC operation of STS to obtain an STS token as the default credential.

3. Obtain the credential information from the config.json file

If no credentials are found in the previous step, the Credentials tool obtains the credential information from the config.json file. The path of the configuration file varies based on the operating system:

Linux: ~/.aliyun/config.json

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

If the config.json file exists, the application initializes a Credentials client by using credential information that is specified by the current parameter in the config.json file. You can also specify the ALIBABA_CLOUD_PROFILE environment variable to specify the credential information. For example, you can set the ALIBABA_CLOUD_PROFILE environment variable to client1.

The mode parameter in the config.json file specifies the method that is used to obtain the credential information. Valid values:

  • AK: uses the AccessKey pair of a RAM user to obtain the credential information.

  • RamRoleArn: uses the ARN of a RAM role to obtain the credential information.

  • EcsRamRole: uses the RAM role attached to an ECS instance to obtain the credential information.

  • OIDC: uses the ARN of an OIDC IdP and the OIDC token file to obtain the credential information.

  • ChainableRamRoleArn: uses a role chain and specifies an access credential in another JSON file to obtain the credential information.

Configuration example:

{
	"current": "default",
	"profiles": [
		{
			"name": "default",
			"mode": "AK",
			"access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
			"access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>"
		},
		{
			"name":"client1",
			"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":"client2",
			"mode":"EcsRamRole",
			"ram_role_name":"<RAM_ROLE_ARN>"
		},
		{
			"name":"client3",
			"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":"client4",
			"mode":"ChainableRamRoleArn",
			"source_profile":"<PROFILE_NAME>",
			"ram_role_arn":"<ROLE_ARN>",
			"ram_session_name":"<ROLE_SESSION_NAME>",
			"expired_seconds":3600
		}
	]
}

4. Obtain the credential information by using the RAM role of an ECS instance

If no credentials are found in the previous step, the Credentials tool obtains the value of the ALIBABA_CLOUD_ECS_METADATA environment variable that specifies the RAM role name of an ECS instance. If the RAM role exists, the application obtains an STS token of the RAM role as the default credential by using the metadata server of ECS in security hardening mode. If an exception occurs in the security hardening mode, the Credentials tool obtains the access credential in normal mode. You can also configure the ALIBABA_CLOUD_IMDSV1_DISABLED environment variable to specify an exception handling logic. Valid values of the environment variable:

  1. false: The Credentials tool continues to obtain the access credential in normal mode.

  2. true: The exception is thrown and the Credentials tool continues to obtain the access credential in security hardening mode.

The configurations for the metadata server determine whether the server supports the security hardening mode.

5. Use a credential URI

If no credentials are found in the previous step, the Credentials tool obtains the value of the ALIBABA_CLOUD_CREDENTIALS_URI environment variable that specifies the URI of the credential. If the URI of the credential exists, the application uses the URI of the credential to obtain an STS token as the default credential.

Switch between credentials

You can use the following method to use different credentials to call different API operations in your application:

Use multiple Credentials clients

Initialize multiple Credentials clients to pass different credentials to different request clients.

import Credential, { Config } from '@alicloud/credentials';

const credentialsConfig1 = new Config({
  type: 'access_key',
  accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
  accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
})
const credentialClient1 = new Credential(credentialsConfig1);

const credentialsConfig2 = new Config({
  type: 'sts',
  accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
  accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
  securityToken: process.env.ALIBABA_CLOUD_SECURITY_TOKEN,
})
const credentialClient2 = new Credential(credentialsConfig2);

References