Todos los productos
Search
Centro de documentos

Alibaba Cloud SDK:Gestión de las credenciales de acceso

Última actualización: Sep 06, 2026

El SDK de Alibaba Cloud utiliza la herramienta Credentials para gestionar de forma centralizada las credenciales, como su AccessKey y su token STS. Este tema describe los tipos de credenciales compatibles y sus métodos de configuración.

Contexto

Las credenciales verifican la identidad de un usuario cuando accede a los servicios de Alibaba Cloud. Los tipos de credenciales más comunes incluyen:

  1. Un par de AccessKey proporciona credenciales permanentes para una cuenta de Alibaba Cloud o un usuario de RAM. Está compuesto por un AccessKey ID y un AccessKey Secret.

  2. Un token STS proporciona credenciales temporales para un rol de RAM con un periodo de validez y un alcance de permisos configurables. What is STS.

  3. Un bearer token se utiliza para la autenticación y la autorización.

Requisitos previos

Instalación de la herramienta Credentials

Ejecute el siguiente comando de npm para instalar el paquete.

npm install @alicloud/credentials

Utilice la versión más reciente para asegurarse de que todos los tipos de credenciales sean compatibles. Releases · aliyun/credentials-nodejs · GitHub.

Parámetros de credenciales

Configure las credenciales mediante el constructor Config del módulo @alicloud/credentials. El parámetro type es obligatorio y determina qué otros parámetros aplican. A continuación se muestra una tabla con los valores válidos de type y sus parámetros correspondientes. √ = obligatorio, - = opcional, × = no compatible.

Nota

Solo se admiten los tipos de credenciales y los parámetros que se enumeran a continuación.

type

access_key

sts

ram_role_arn

ecs_ram_role

oidc_role_arn

credentials_uri

bearer

accessKeyId: el AccessKey ID.

√

√

√

×

×

×

×

accessKeySecret: el AccessKey secret.

√

√

√

×

×

×

×

securityToken: el token de Security Token Service (STS).

×

√

-

×

×

×

×

roleArn: el nombre de recurso de Alibaba Cloud (ARN) del rol de RAM.

×

×

√

×

√

×

×

roleSessionName: un nombre personalizado para la sesión. El formato predeterminado es credentials-nodejs-<timestamp>.

×

×

-

×

-

×

×

roleName: el nombre del rol de RAM.

×

×

×

-

×

×

×

disableIMDSv1: indica si se debe aplicar el modo de refuerzo de seguridad (IMDSv2). Valor predeterminado: false.

×

×

×

-

×

×

×

bearerToken: el bearer token.

×

×

×

×

×

×

√

policy: una política personalizada.

×

×

-

×

-

×

×

roleSessionExpiration: el tiempo de expiración de la sesión, en segundos. Valor predeterminado: 3600.

×

×

-

×

-

×

×

oidcProviderArn: el ARN del proveedor de identidades de OpenID Connect (OIDC).

×

×

×

×

√

×

×

oidcTokenFilePath: la ruta del archivo de token de OpenID Connect (OIDC).

×

×

×

×

√

×

×

externalId: un ID externo para mitigar el problema del delegado confuso. Use an external ID to prevent the confused deputy problem.

×

×

-

×

×

×

×

credentialsURI: el URI de las credenciales.

×

×

×

×

×

√

×

El endpoint de STS. Admite endpoints de VPC y públicos. Endpoints disponibles: Endpoints. Valor predeterminado: sts.aliyuncs.com.

×

×

-

×

-

×

×

timeout: el tiempo de espera de lectura para las solicitudes HTTP, en milisegundos. El valor predeterminado es 5000.

×

×

-

-

-

-

×

connectTimeout: el tiempo de espera de conexión para las solicitudes HTTP, en milisegundos. El valor predeterminado es 10000.

×

×

-

-

-

-

×

Inicialización de un cliente de credenciales

La sección anterior describe los tipos de credenciales y los parámetros de configuración que admite la herramienta Credentials. En las siguientes secciones se proporcionan ejemplos de código que muestran cómo utilizar esta herramienta. Seleccione el método que mejor se adapte a su escenario.

Importante
  • Nunca almacene un AccessKey en texto plano dentro del código de su proyecto. Una clave expuesta compromete todos los recursos asociados a la cuenta. Almacénela en variables de entorno o en archivos de configuración.

  • Implemente el singleton pattern para la credentials tool. Esto habilita la credential cache integrada y evita el rate limiting provocado por un exceso de llamadas a la API. Credential auto-refresh mechanism for session credentials.

Método 1: cadena de proveedores de credenciales predeterminada

Si inicializa un cliente de credenciales sin parámetros, se activa la 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);
});

Llamada a la API

Este ejemplo muestra cómo llamar a la operación DescribeRegions de ECS. Para ejecutar el código, debe instalar el SDK de ECS.

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);
});

Método 2: uso de un AccessKey

La herramienta Credentials utiliza el AccessKey que usted proporciona como credencial de acceso.

Aviso

Una cuenta de Alibaba Cloud (cuenta raíz) tiene permisos completos sobre todos sus recursos, por lo que exponer su AK representa un riesgo de seguridad importante. No utilice el AK de una cuenta raíz.

Utilice el AK de un usuario de RAM con permisos de mínimo privilegio.

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);

Llamada a la API

Este ejemplo llama a la operación DescribeRegions de ECS. Debe instalar el SDK de ECS para ejecutar el código.

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);
});

Método 3: uso de un token STS

La herramienta Credentials utiliza el STS token estático que usted proporciona como credencial de acceso.

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);

Llamada a la API

Este ejemplo llama a la operación DescribeRegions de ECS. Para ejecutar este código, debe instalar el SDK de ECS y el SDK de Security Token Service.

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);

Método 4: AccessKey y ARN de rol de RAM

Este método utiliza STS de forma interna. Cuando usted especifica el ARN de un rol de RAM, la herramienta Credentials obtiene un token STS desde STS. Puede usar el parámetro policy para restringir aún más los permisos del rol.

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);

Método de llamada a la API

Este ejemplo muestra cómo llamar a la operación DescribeRegions de ECS. Para ejecutar el código, debe instalar el SDK de ECS.

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);
});

Método 5: rol de RAM de instancia de ECS

Asigne un rol de RAM de instancia a una instancia de ECS o a una instancia de contenedor elástico. Las aplicaciones alojadas en la instancia podrán usar la herramienta Credentials para obtener automáticamente un token STS asociado a ese rol.

De forma predeterminada, la herramienta Credentials accede al servidor de metadatos de ECS en modo de refuerzo de seguridad (IMDSv2). Si ocurre un error, recurre al modo normal. Controle este comportamiento con el parámetro disableIMDSv1 o con la variable de entorno ALIBABA_CLOUD_IMDSV1_DISABLE:

  • false (valor predeterminado): recurre al modo normal si se produce un error.

  • true: utiliza únicamente el modo de refuerzo de seguridad y genera una excepción si falla.

La compatibilidad con IMDSv2 depende de la configuración de su servidor.

También puede deshabilitar el acceso a las credenciales a través de los metadatos de ECS si establece la variable de entorno ALIBABA_CLOUD_ECS_METADATA_DISABLED=true.

Nota
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);

Llamada a la API

Este ejemplo llama a la operación DescribeRegions de ECS. Para ejecutar el código, primero instale el SDK de ECS.

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);
});

Método 6: uso de OIDCRoleArn

Si utiliza OIDC y cuenta con created a RAM role for an OIDC provider, pase un ARN de proveedor de OIDC, un token de OIDC y un ARN de rol de RAM al SDK de Credentials. El SDK llama a la operación AssumeRoleWithOIDC para obtener un token de STS. Estas credenciales admiten la actualización automática. Auto-refresh mechanism for session credentials. Por ejemplo, en un clúster de ACK con RRSA habilitado, el SDK lee la configuración de OIDC desde las variables de entorno del Pod y obtiene un token de STS para acceder a los servicios de Alibaba Cloud.

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

Este ejemplo muestra cómo llamar a la operación DescribeRegions de ECS. Para ejecutar el código, instale el SDK de ECS.

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);
});

Método 7: credencial URI

Exponga el servicio de STS mediante una URI para que los servicios externos obtengan un token de STS sin manejar pares de AccessKey directamente. La herramienta de Credentials recupera un token de STS de la URI especificada y lo usa como credencial de acceso, con compatibilidad para actualización automática. 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);

La respuesta de la URI debe cumplir con los siguientes requisitos:

  • El código de estado es 200.

  • Formato del cuerpo de la respuesta:

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

API call

Este ejemplo demuestra cómo llamar a la operación DescribeRegions de ECS. Antes de ejecutar el código, instale el SDK de ECS.

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);
});

Método 8: uso de un bearer token

Actualmente, solo Alibaba Cloud Call Center (CCC) admite la autenticación mediante bearer token.

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

Este ejemplo muestra cómo llamar a la operación GetInstance de Cloud Call Center (CCC). Para ejecutar el código, instale el SDK de Cloud Call Center.

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);
});

Cadena predeterminada de proveedores de credenciales

La cadena predeterminada de proveedores de credenciales le permite usar el mismo código en distintos entornos y controlar la recuperación de credenciales mediante configuración externa. Cuando llama a new Credential() sin parámetros, el SDK busca las credenciales en el siguiente orden.

1. Uso de variables de entorno

Si no se encuentra ninguna credencial en las propiedades del sistema, la cadena de proveedores comprueba las variables de entorno.

  • Si ALIBABA_CLOUD_ACCESS_KEY_ID y ALIBABA_CLOUD_ACCESS_KEY_SECRET están presentes y no están vacíos, la cadena de proveedores los usa como credencial predeterminada.

  • Si también se establecen ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET y ALIBABA_CLOUD_SECURITY_TOKEN, la cadena de proveedores usa un token de STS como credencial predeterminada.

2. Roles de RAM de OIDC

Si no se ha encontrado ninguna credencial, la cadena de proveedores comprueba las siguientes variables de entorno relacionadas con un rol de RAM de OIDC:

  • ALIBABA_CLOUD_ROLE_ARN: el ARN del rol de RAM.

  • ALIBABA_CLOUD_OIDC_PROVIDER_ARN: el ARN del proveedor de OIDC.

  • ALIBABA_CLOUD_OIDC_TOKEN_FILE: la ruta del archivo del token de OIDC.

Si las tres variables de entorno están presentes y no están vacías, la cadena de proveedores usa estos valores para llamar a la API AssumeRoleWithOIDC de Security Token Service (STS) y obtener un token de STS.

3. Config.json

Si no se ha encontrado ninguna credencial, la cadena de proveedores intenta cargar el archivo de credenciales compartidas, config.json, desde su ubicación predeterminada y usa la credencial especificada en dicho archivo.

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

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

Para configurar una credencial de esta manera, utilice Alibaba Cloud CLI o cree manualmente un archivo config.json en la ruta correspondiente. A continuación se muestra el formato del contenido:

{
  "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
    }
  ]
}

Parámetro

Descripción

current

Especifique el nombre de la credencial para recuperar la configuración correspondiente. Este nombre corresponde al valor del parámetro name dentro de profiles. De forma predeterminada, el sistema da prioridad al nombre indicado por la variable de entorno ALIBABA_CLOUD_PROFILE. Si dicha variable no está configurada, el sistema usa el nombre definido en current.

profiles

Contiene una colección de configuraciones de credenciales. El parámetro mode indica el tipo de credencial:

  • AK: usa el AccessKey de un usuario de RAM como credencial.

  • StsToken: usa un token de STS como credencial.

  • RamRoleArn: asume un rol de RAM mediante las credenciales de un usuario de RAM para obtener una credencial temporal.

  • EcsRamRole: obtiene una credencial a partir de los metadatos de la instancia.

  • OIDC: obtiene una credencial mediante un ARN de proveedor de OIDC, un token de OIDC y un ARN de rol de RAM.

  • ChainableRamRoleArn: usa el encadenamiento de roles para obtener una nueva credencial. Toma como base una credencial inicial de profiles, indicada por el parámetro source_profile.

4. Rol de RAM de la instancia de ECS

Si no se encuentran credenciales de mayor prioridad, el SDK recupera las credenciales del rol de RAM de la instancia de ECS. Para ello, accede al servicio de metadatos de la instancia en modo mejorado (IMDSv2) y obtiene un token de STS. Este proceso requiere dos solicitudes: una para el nombre del rol y otra para las credenciales. Para reducirlo a una sola solicitud, establezca el nombre del rol en la variable de entorno ALIBABA_CLOUD_ECS_METADATA. Si el modo mejorado falla, el proceso recurre al modo normal. Controle este comportamiento con ALIBABA_CLOUD_IMDSV1_DISABLE:

  1. false: recurre al modo normal si ocurre un error.

  2. true: usa únicamente el modo mejorado y genera una excepción si falla.

La compatibilidad con IMDSv2 depende de la configuración del servicio de metadatos de la instancia.

Para deshabilitar la recuperación de credenciales desde los metadatos de la instancia de ECS, establezca ALIBABA_CLOUD_ECS_METADATA_DISABLED=true.

Nota

5. URI de credenciales

Si no se ha encontrado ninguna credencial, la cadena de proveedores comprueba la variable de entorno ALIBABA_CLOUD_CREDENTIALS_URI. Si esta variable está configurada y apunta a una URI válida, la cadena accede a dicha URI para recuperar un token de STS.

Actualización automática de credenciales de sesión

Las credenciales de sesión (ram_role_arn, ecs_ram_role, oidc_role_arn y credentials_uri) incluyen actualización automática integrada. En la primera recuperación, la herramienta de credenciales almacena la credencial en la caché. Las solicitudes posteriores devuelven el valor almacenado hasta que caduca; en ese momento, se obtiene automáticamente una credencial nueva.

Nota

En el caso de las credenciales ecs_ram_role, la herramienta de credenciales las actualiza de forma proactiva 15 minutos antes de que caduquen.

El siguiente ejemplo usa el patrón singleton para crear un cliente de credenciales. Compruebe la actualización automática recuperando las credenciales en distintos intervalos y valide su vigencia mediante una llamada a OpenAPI.

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

Análisis basado en la salida del registro:

  • En la primera llamada, la caché está vacía. El sistema recupera una credencial según su configuración y luego la almacena en la caché.

  • La segunda llamada usa la misma credencial que la primera, lo cual indica que se recuperó de la caché.

  • En la tercera llamada, la credencial almacenada ya caducó. Su tiempo de expiración (RoleSessionExpiration) es de 3600 segundos, pero esta llamada se ejecuta 4200 segundos después de la primera. Por lo tanto, el mecanismo de actualización automática del SDK obtiene una credencial nueva y actualiza la caché.

  • La cuarta llamada usa la misma credencial que la tercera, lo que confirma que la caché se actualizó correctamente.

Documentos relacionados