Todos los productos
Search
Centro de documentos

Alibaba Cloud SDK:Gestionar credenciales de acceso

Última actualización: Sep 05, 2026

El SDK de Alibaba Cloud utiliza la herramienta Credentials para gestionar de forma centralizada las credenciales, como su AccessKey y su STS Token. 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 un sistema. Los tipos más comunes son:

  1. Un par de AccessKey (AK) es una credencial permanente para una cuenta de Alibaba Cloud o un usuario de RAM. Está formado por un AccessKey ID y un AccessKey Secret.

  2. Un token de STS es una credencial de seguridad temporal para un rol de RAM de Alibaba Cloud. Su validez y permisos se pueden personalizar. What is STS.

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

Requisitos previos

  • Se requiere PHP 5.6 o posterior. Se recomienda ampliamente usar la extensión cURL con cURL 7.16.2+ y un backend TLS.

  • Se requiere el SDK de Alibaba Cloud V2.0.

Instalar credentials

Con Composer instalado de forma global, ejecute este comando para agregar Alibaba Cloud Credentials para PHP:

composer require alibabacloud/credentials
  • Utilice la versión más reciente para asegurar la compatibilidad con todos los tipos de credenciales.

  • Todas las versiones publicadas se enumeran en el CHANGELOG.

Parámetros de credenciales

Los parámetros de configuración se definen en AlibabaCloud\Credentials\Credential\Config. Establezca el parámetro obligatorio type para especificar el tipo de credencial y luego configure los parámetros correspondientes. A continuación se muestra una tabla que enumera los valores de type y los parámetros compatibles, donde √ = obligatorio, - = opcional y × = no compatible.

Nota

No utilice tipos de credenciales ni parámetros que no aparezcan en la tabla.

Parámetro

access_key

sts

ram_role_arn

ecs_ram_role

oidc_role_arn

credentials_uri

bearer

accessKeyId: El Access Key ID.

√

√

√

×

×

×

×

accessKeySecret: El secreto del Access Key.

√

√

√

×

×

×

×

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

×

√

-

×

×

×

×

roleArn: El Alibaba Cloud Resource Name (ARN) del rol de RAM.

×

×

√

×

√

×

×

roleSessionName: Un nombre de sesión personalizado. El valor predeterminado es phpSdkRoleSessionName.

×

×

-

×

-

×

×

roleName: El nombre del rol de RAM.

×

×

×

-

×

×

×

disableIMDSv1: Especifica si se aplica el modo de refuerzo de seguridad. El valor predeterminado es false.

×

×

×

-

×

×

×

bearerToken: El bearer token.

×

×

×

×

×

×

√

policy: Una política personalizada.

×

×

-

×

-

×

×

roleSessionExpiration: El tiempo de expiración de la sesión en segundos. El valor predeterminado es 3600.

×

×

-

×

-

×

×

oidcProviderArn: El Alibaba Cloud Resource Name (ARN) del proveedor de identidades OIDC.

×

×

×

×

√

×

×

oidcTokenFilePath: La ruta del archivo del token OIDC.

×

×

×

×

√

×

×

externalId: El ID externo del rol de RAM, que se usa para evitar confused deputy problem.

×

×

-

×

×

×

×

credentialsURI: El URI de la credencial.

×

×

×

×

×

√

×

STSEndpoint: El endpoint de STS. Son compatibles tanto los endpoints de VPC como los públicos. Valores válidos: Endpoints. Valor predeterminado: sts.aliyuncs.com.

×

×

-

×

-

×

×

timeout: El tiempo de espera de lectura HTTP en milisegundos. El valor predeterminado es 5000.

×

×

-

-

-

-

×

connectTimeout: El tiempo de espera de conexión HTTP en milisegundos. El valor predeterminado es 10000.

×

×

-

-

-

-

×

Inicializar un cliente de credenciales

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

Importante
  • Almacenar un AccessKey en texto plano representa un riesgo de seguridad. Si un repositorio se configura de forma incorrecta, el AccessKey queda expuesto y compromete todos los recursos de la cuenta. Almacene los AccessKeys en variables de entorno o archivos de configuración.

  • Utilice el patrón singleton con la herramienta Credentials. Esto habilita la caché de credenciales integrada, evita la limitación de velocidad por llamadas frecuentes a la API y previene el desperdicio de recursos al crear varias instancias. Automatic refresh mechanism for Session credentials.

Método 1: Usar la cadena de proveedores de credenciales predeterminada

Un cliente de Credentials inicializado sin parámetros utiliza default credential provider chain.

<?php

use AlibabaCloud\Credentials\Credential;

// Use the Composer autoloader by requiring the autoload.php file from the vendor directory.
require_once 'vendor/autoload.php';

// No parameters specified.
$credClient = new Credential();

$credential = $credClient->getCredential();
$credential->getAccessKeyId();
$credential->getAccessKeySecret();

Ejemplo de llamada a la API

Este ejemplo muestra cómo llamar a la API DescribeRegions de ECS. Antes de empezar, instale el SDK de ECS para PHP.

<?php

use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\SDK\Ecs\V20140526\Ecs as Ecs;
use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeRegionsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;

// Enable Composer autoloading via the vendor/autoload.php file.
require_once 'vendor/autoload.php';

// Initialize the client with the default credential.
$credentialClient = new Credential();
$ecsConfig = new Config([
    // Set the credential for the client configuration.
    'credential' => $credentialClient,
    // Specify the service endpoint.
    'endpoint' => 'ecs.aliyuncs.com'
]);
// Initialize the ECS client.
$ecsClient = new Ecs($ecsConfig);
// Initialize the request object.
$describeRegionsRequest = new DescribeRegionsRequest([]);
// Initialize runtime options.
$runtime = new RuntimeOptions([]);
$resp = $ecsClient->describeRegionsWithOptions($describeRegionsRequest, $runtime);
// Print the HTTP status code.
echo $resp->statusCode;
// Print the response object.
var_dump($resp);

Método 2: Usar un AccessKey

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

Aviso

Una cuenta de Alibaba Cloud (cuenta raíz) tiene permisos totales 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.

<?php

use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\Credentials\Credential\Config;

// Enable the Composer autoloader.
require_once 'vendor/autoload.php';

$credConfig = new Config([
    'type' => 'access_key',
    'accessKeyId' => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    'accessKeySecret' => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
]);

$credClient = new Credential($credConfig);

$credential = $credClient->getCredential();
$credential->getAccessKeyId();
$credential->getAccessKeySecret();

Ejemplo de API

Este ejemplo demuestra cómo llamar a la operación DescribeRegions. Para ello, primero debe instalar el SDK de ECS.

<?php

namespace AlibabaCloud\SDK\Sample;

use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\Credentials\Credential\Config as CredentialConfig;
use AlibabaCloud\SDK\Ecs\V20140526\Ecs as Ecs;
use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeRegionsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;

// Enable autoloading for Composer by using the autoload.php file in the vendor directory.
require_once 'vendor/autoload.php';

// Initialize a credential object with an AccessKey pair.
$credConfig = new CredentialConfig([
    'type' => 'access_key',
    'accessKeyId' => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    'accessKeySecret' => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
]);
$credClient = new Credential($credConfig);

$ecsConfig = new Config([
    // Set the credential for the configuration.
    'credential' => $credClient,
    // Specify the service endpoint.
    'endpoint' => 'ecs.aliyuncs.com'
]);
// Initialize the ECS client.
$ecsClient = new Ecs($ecsConfig);
// Initialize the request object.
$describeRegionsRequest = new DescribeRegionsRequest([]);
// Initialize runtime configurations.
$runtime = new RuntimeOptions([]);
$resp = $ecsClient->describeRegionsWithOptions($describeRegionsRequest, $runtime);
// Print the status code.
echo $resp->statusCode;
// Print the response.
var_dump($resp);

Método 3: Usar un token de STS

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

<?php

use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\Credentials\Credential\Config;

// Include 'vendor/autoload.php' to enable Composer autoloading.
require_once 'vendor/autoload.php';

$credConfig = new Config([
    'type' => 'sts',
    // Get the AccessKey ID from the environment variable.
    'accessKeyId' => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    // Get the AccessKey Secret from the environment variable.
    'accessKeySecret' => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    // Get the security token from the environment variable.
    'securityToken' => getenv('ALIBABA_CLOUD_SECURITY_TOKEN'),
]);
$credClient = new Credential($credConfig);

$credential = $credClient->getCredential();
$credential->getAccessKeyId();
$credential->getAccessKeySecret();
$credential->getSecurityToken();

Ejemplo de API

Este ejemplo llama a la operación DescribeRegions de ECS. Primero, instale el SDK de ECS y el SDK de STS.

<?php

namespace AlibabaCloud\SDK\Sample;

use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\Credentials\Credential\Config as CredentialConfig;
use AlibabaCloud\SDK\Ecs\V20140526\Ecs as Ecs;
use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeRegionsRequest;
use AlibabaCloud\SDK\Sts\V20150401\Models\AssumeRoleRequest;
use AlibabaCloud\SDK\Sts\V20150401\Sts;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;

// Enable autoloading for Composer by using the autoload.php file in the vendor directory.
require_once 'vendor/autoload.php';

// Create an STS client and call the AssumeRole operation to obtain temporary credentials.
$config = new Config([
    // Retrieve the AccessKey ID and AccessKey Secret from environment variables. Ensure these variables are set before you run the code.
    'accessKeyId' => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    'accessKeySecret' => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    'endpoint' => 'sts.aliyuncs.com',
]);
$stsClient = new Sts($config);
$request = new AssumeRoleRequest([
    // The RAM role ARN to assume. Example: acs:ram::123456789012****:role/adminrole. You can set this by using the ALIBABA_CLOUD_ROLE_ARN environment variable.  
    'roleArn' => '<RoleArn>',
    // The role session name. You can set this by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.  
    'roleSessionName' => '<RoleSessionName>',
]);
$assumeRoleResp = $stsClient->assumeRole($request);
$assumeRoleCredentials = $assumeRoleResp->body->credentials;

// Initialize the Credential client with the retrieved temporary credentials.
$credentialConfig = new CredentialConfig([
    // The credential type.
    'type' => 'sts',
    'accessKeyId' => $assumeRoleCredentials->accessKeyId,
    'accessKeySecret' => $assumeRoleCredentials->accessKeySecret,
    'securityToken' => $assumeRoleCredentials->securityToken,
]);
$credentialClient = new Credential($credentialConfig);
$ecsConfig = new Config([
    // Use the Credential client for authentication.
    'credential' => $credentialClient,
    // The service endpoint for ECS.
    'endpoint' => 'ecs.aliyuncs.com'
]);// Initialize the ECS client.
$ecsClient = new Ecs($ecsConfig);// Initialize the request.
$describeRegionsRequest = new DescribeRegionsRequest([]);// Initialize runtime options.
$runtime = new RuntimeOptions([]);
$resp = $ecsClient->describeRegionsWithOptions($describeRegionsRequest, $runtime);// Print the status code.
echo $resp->statusCode;// Print the response.
var_dump($resp);

Método 4: Usar un AccessKey y el ARN de un rol de RAM

Este método obtiene un token de STS al asumir un rol de RAM. Usted puede asignar una policy para limitar los permisos de la sesión.

<?php

use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\Credentials\Credential\Config;

// Include the Composer autoloader.
require_once 'vendor/autoload.php';

$credConfig = new Config([
    'type' => 'ram_role_arn',
    'accessKeyId' => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    'accessKeySecret' => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    // The ARN for the RAM role to assume. Can be set with the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole.
    'roleArn' => '<RoleArn>',
    // A custom role session name. Can be set with the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
    'roleSessionName' => '<RoleSessionName>',
    // Optional. A policy that further restricts the session's permissions. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}.
    'policy' => '<Policy>',
    // Optional. The session expiration in seconds. Default value: 3600.
    'roleSessionExpiration' => 3600,
]);
$credClient = new Credential($credConfig);

$credential = $credClient->getCredential();
$credential->getAccessKeyId();
$credential->getAccessKeySecret();
$credential->getSecurityToken();

Ejemplo de llamada a la API

Este ejemplo muestra cómo llamar a la operación DescribeRegions de ECS. Primero debe instalar el SDK de ECS.

<?php

namespace AlibabaCloud\SDK\Sample;

// Enable autoloading for Composer by using the autoload.php file in the vendor directory.
require_once 'vendor/autoload.php';

use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\Credentials\Credential\Config as CredentialConfig;
use AlibabaCloud\SDK\Ecs\V20140526\Ecs as Ecs;
use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeRegionsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;

// Use an AccessKey pair and a RAM role ARN to initialize the Credentials client.
$credentialConfig = new CredentialConfig([
    // The credential type.
    'type' => 'ram_role_arn',
    // Obtain the AccessKey ID from the environment variable.
    'accessKeyId' => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    // Obtain the AccessKey secret from the environment variable.
    'accessKeySecret' => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    // The ARN of the RAM role to assume. You can also set this using the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole
    'roleArn' => '<RoleArn>',
    // 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 further restrict the session's permissions. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    'policy' => '<Policy>',
    // Optional. The session expiration, in seconds. Default: 3600.
    'roleSessionExpiration' => 3600,
]);
$credentialClient = new Credential($credentialConfig);

$ecsConfig = new Config([
    // The credential to use for authentication.
    'credential' => $credentialClient,
    // The service endpoint.
    'endpoint' => 'ecs.aliyuncs.com'
]);
// Initialize the ECS client.
$ecsClient = new Ecs($ecsConfig);
// Initialize the request object.
$describeRegionsRequest = new DescribeRegionsRequest([]);
// Initialize runtime options.
$runtime = new RuntimeOptions([]);
$resp = $ecsClient->describeRegionsWithOptions($describeRegionsRequest, $runtime);
// Print the status code.
echo $resp->statusCode;
// Print the response.
var_dump($resp);

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

Asigne un rol de RAM de instancia a las instancias de ECS o ECI. Las aplicaciones en estas instancias pueden usar la herramienta Credentials para obtener un token de STS automáticamente.

De forma predeterminada, la herramienta Credentials accede al servicio de metadatos de ECS en modo de refuerzo de seguridad (IMDSv2) y vuelve al modo normal si falla. Controle este comportamiento con el parámetro disableIMDSv1 o con la variable de entorno ALIBABA_CLOUD_IMDSV1_DISABLE:

  • Si se establece en false (valor predeterminado), la herramienta vuelve al modo normal.

  • Si se establece en true, la herramienta solo utiliza el modo de refuerzo de seguridad y lanza una excepción si falla, sin volver al modo normal.

Sus configuraciones del lado del servidor determinan si este admite IMDSv2.

Para deshabilitar el acceso a credenciales desde los metadatos de ECS, establezca la variable de entorno ALIBABA_CLOUD_ECS_METADATA_DISABLED=true.

Nota
<?php

use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\Credentials\Credential\Config;

// Enable autoloading for Composer by using the autoload.php file in the vendor directory.
require_once 'vendor/autoload.php';

$credConfig = new Config([
    'type' => 'ecs_ram_role',
    // Optional. The name of the ECS RAM role. If not specified, the role name is automatically retrieved. Specifying this parameter reduces requests. You can also set the role name by using the ALIBABA_CLOUD_ECS_METADATA environment variable.
    'roleName' => '<RoleName>',
    // Optional. Defaults to false. When set to true, this enforces security hardening mode. When false, the system first tries to retrieve the credential in security hardening mode and falls back to normal mode (IMDSv1) on failure.
    // 'disableIMDSv1' => true,
]);
$credClient = new Credential($credConfig);

$credential = $credClient->getCredential();
$credential->getAccessKeyId();
$credential->getAccessKeySecret();
$credential->getSecurityToken();

Llamada a la API

Este ejemplo demuestra cómo llamar a la operación DescribeRegions de ECS. Debe instalar el SDK de ECS para ejecutar este ejemplo.

<?php

namespace AlibabaCloud\SDK\Sample;

// Use Composer's autoload mechanism by requiring the autoload.php file in the vendor directory.
require_once 'vendor/autoload.php';

use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\Credentials\Credential\Config as CredentialConfig;
use AlibabaCloud\SDK\Ecs\V20140526\Ecs as Ecs;
use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeRegionsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;

// Initialize the Credentials client with an ECS instance RAM role.
$credConfig = new CredentialConfig([
    'type' => 'ecs_ram_role',
    // Optional. The name of the ECS instance RAM role. If omitted, the role name is retrieved automatically. Specifying this parameter reduces API calls. You can also set the role name using the ALIBABA_CLOUD_ECS_METADATA environment variable.
    'roleName' => '<RoleName>',
]);
$credClient = new Credential($credConfig);

$ecsConfig = new Config([
    // Use the Credential client to configure credentials.
    'credential' => $credClient,
    // The service endpoint.
    'endpoint' => 'ecs.aliyuncs.com'
]);
// Initialize the ECS client.
$ecsClient = new Ecs($ecsConfig);
// Initialize the request object.
$describeRegionsRequest = new DescribeRegionsRequest([]);
// Initialize the runtime options.
$runtime = new RuntimeOptions([]);
$resp = $ecsClient->describeRegionsWithOptions($describeRegionsRequest, $runtime);
// Print the status code.
echo $resp->statusCode;
// Print the response.
var_dump($resp);

Método 6: Usar el ARN de un rol OIDC

Después de creating a RAM role for an OIDC identity provider, pase el ARN del proveedor OIDC, el token OIDC y el ARN del rol de RAM a la herramienta Credentials. Esta herramienta llama a AssumeRoleWithOIDC para obtener un token de STS, con Automatic refresh mechanism for session credentials. Por ejemplo, en un clúster de ACK con RRSA habilitado, la herramienta lee la configuración de OIDC desde las variables de entorno del Pod y obtiene un token de STS para el rol de servicio.

<?php

use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\Credentials\Credential\Config as CredentialConfig;

// Enable autoloading for Composer by using the autoload.php file in the vendor directory.
require_once 'vendor/autoload.php';

// Initialize a credential client to assume a RAM role via an OIDC IdP.
$credConfig = new CredentialConfig([
    // The credential type.
    'type' => 'oidc_role_arn',
    // The OIDC provider ARN. Can also be set via the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
    'oidcProviderArn' => '<OidcProviderArn>',
    // The OIDC token file path. Can also be set via the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
    'oidcTokenFilePath' => '<OidcTokenFilePath>',
    // The RAM role ARN to assume. Can also be set via the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole.
    'roleArn' => '<RoleArn>',
    // The custom role session name. Can also be set via the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
    'roleSessionName' => '<RoleSessionName>',
    // Optional. A more restrictive session policy. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}.
    'policy' => '<Policy>',
    // Optional. The session expiration, in seconds.
    'roleSessionExpiration' => 3600,
]);

$credClient = new Credential($credConfig);

$credential = $credClient->getCredential();
$credential->getAccessKeyId();
$credential->getAccessKeySecret();
$credential->getSecurityToken();

Ejemplo de llamada a la API

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

<?php

namespace AlibabaCloud\SDK\Sample;

// Enable autoloading for Composer by using the autoload.php file in the vendor directory.
require_once 'vendor/autoload.php';

use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\Credentials\Credential\Config as CredentialConfig;
use AlibabaCloud\SDK\Ecs\V20140526\Ecs as Ecs;
use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeRegionsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;

// Initialize the Credential client to use an OIDC-based RAM role.
$credConfig = new CredentialConfig([
    // The credential type.
    'type' => 'oidc_role_arn',
    // The OIDC provider ARN. You can set this by using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
    'oidcProviderArn' => '<OidcProviderArn>',
    // The OIDC token file path. You can set this by using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
    'oidcTokenFilePath' => '<OidcTokenFilePath>',
    // The RAM role ARN to assume. You can set this by using the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole.
    'roleArn' => '<RoleArn>',
    // A custom role session name. You can set this by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
    'roleSessionName' => '<RoleSessionName>',
    // Optional. A more restrictive session policy. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}.
    'policy' => '<Policy>',
    // Optional. The session expiration, in seconds.
    'roleSessionExpiration' => 3600,
]);

$credClient = new Credential($credConfig);

$ecsConfig = new Config([
    // The authentication credential.
    'credential' => $credClient,
    // The service endpoint.
    'endpoint' => 'ecs.aliyuncs.com'
]);
// Initialize the ECS client.
$ecsClient = new Ecs($ecsConfig);
// Initialize the request object.
$describeRegionsRequest = new DescribeRegionsRequest([]);
// Initialize runtime configurations.
$runtime = new RuntimeOptions([]);
$resp = $ecsClient->describeRegionsWithOptions($describeRegionsRequest, $runtime);
// Print the status code.
echo $resp->statusCode;
// Print the response.
var_dump($resp);

Método 7: Usar una credencial URI

Envuelva un servicio de STS detrás de un URI para evitar exponer los AccessKeys. La herramienta Credentials recupera un token de STS desde el URI y lo actualiza automáticamente. Automatic refresh for session-type credentials.

<?php

namespace AlibabaCloud\SDK\Sample;

use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\Credentials\Credential\Config;

// Enable Composer autoloading by including the vendor/autoload.php file.
require_once 'vendor/autoload.php';

// Use a URI credential to initialize the credential client.
$credConfig = new Config([
    // The credential type.
    'type' => 'credentials_uri',
    // The credential URI, for example, http://local_or_remote_uri/. Alternatively, set the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
    'credentialsURI' => '<CredentialsUri>',
]);
$credClient = new Credential($credConfig);

$credential = $credClient->getCredential();
$credential->getAccessKeyId();
$credential->getAccessKeySecret();
$credential->getSecurityToken();

El URI debe cumplir con los siguientes requisitos:

  • Admite solicitudes GET.

  • Devuelve un código de estado 200.

  • El cuerpo de la respuesta es un objeto JSON con los siguientes campos:

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

Llamada a la API

Para usar este ejemplo y llamar a la API DescribeRegions de ECS, primero debe instalar el SDK de ECS.

<?php

namespace AlibabaCloud\SDK\Sample;

// Include the Composer autoloader.
require_once 'vendor/autoload.php';

use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\Credentials\Credential\Config as CredentialConfig; 
use AlibabaCloud\SDK\Ecs\V20140526\Ecs as Ecs;
use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeRegionsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;

// Initialize the Credentials client with a URI credential.
$credConfig = new CredentialConfig([
    // The credential type.
    'type' => 'credentials_uri',
    // The URI of the credential, such as http://local_or_remote_uri/. This can also be set with the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
    'credentialsURI' => '<CredentialsUri>',
]);
$credClient = new Credential($credConfig);

$ecsConfig = new Config([
    // The credential object for authentication.
    'credential' => $credClient,
    // The service endpoint.
    'endpoint' => 'ecs.aliyuncs.com'
]);
// Initialize the ECS client.
$ecsClient = new Ecs($ecsConfig);
// Initialize the request.
$describeRegionsRequest = new DescribeRegionsRequest([]);
// Initialize the runtime configuration.
$runtime = new RuntimeOptions([]);
$resp = $ecsClient->describeRegionsWithOptions($describeRegionsRequest, $runtime);
// Print the status code.
echo $resp->statusCode;
// Print the response.
var_dump($resp);

Método 8: Usar un bearer token

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

<?php

use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\Credentials\Credential\Config;

// Load the Composer autoloader.
require_once 'vendor/autoload.php';

$credConfig = new Config([
    'type' => 'bearer',
    // Set your bearer token.
    'bearerToken' => '<BearerToken>',
]);
$credClient = new Credential($credConfig);

$credential = $credClient->getCredential();
$credential->getBearerToken();

Ejemplo de API

Este ejemplo muestra cómo llamar a la operación GetInstance de Cloud Call Center (CCC). Primero debe instalar el SDK de CCC.

<?php

namespace AlibabaCloud\SDK\Sample;

// Enable autoloading for Composer by using the autoload.php file in the vendor directory.
require_once 'vendor/autoload.php';

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Credentials\Credential\Config as CredentialConfig; 
use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\CCC\V20200701\CCC;
use AlibabaCloud\SDK\CCC\V20200701\Models\GetInstanceRequest;

// Use a bearer token to initialize the credential.
$credConfig = new CredentialConfig([
    // The credential type.
    'type' => 'bearer',
    // Specify the bearer token.
    'bearerToken' => '<BearerToken>',
]);
$credClient = new Credential($credConfig);

$config = new Config([
    // The credential used for authentication.
    'credential' => $credClient,
    // The service endpoint.
    'endpoint' => 'ccc.cn-shanghai.aliyuncs.com'
]);
$cccClient = new CCC($config);
// Initialize the request object.
$getInstanceRequest = new GetInstanceRequest([
    "instanceId" => "ccc-test"
]);
// Initialize runtime configurations.
$runtime = new RuntimeOptions([]);
$resp = $cccClient->getInstanceWithOptions($getInstanceRequest, $runtime);
// Print the status code.
echo $resp->statusCode;
// Print the response.
var_dump($resp);

Cadena predeterminada de proveedores de credenciales

La cadena predeterminada de proveedores de credenciales le permite usar una misma base de código en distintos entornos. Para ello, controla la obtención de credenciales mediante una configuración externa. Cuando se inicializa sin parámetros con $credential = new Credential();, el SDK busca las credenciales en el siguiente orden:

1. 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 utiliza como credencial predeterminada.

  • Si también se definen 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. Rol de RAM para un IdP OIDC

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

  • ALIBABA_CLOUD_ROLE_ARN: El ARN del rol de RAM.

  • ALIBABA_CLOUD_OIDC_PROVIDER_ARN: El ARN del proveedor OIDC.

  • ALIBABA_CLOUD_OIDC_TOKEN_FILE: La ruta del archivo del token OIDC.

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

3. Archivo 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 utiliza 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 de credenciales correspondiente. El nombre de la credencial es el valor del parámetro name dentro de profiles. De forma predeterminada, el sistema da prioridad al nombre de credencial que indica la variable de entorno ALIBABA_CLOUD_PROFILE . Si esta variable de entorno no está configurada, el sistema utiliza el nombre de credencial especificado en current.

profiles

Contiene un conjunto de configuraciones de credenciales. El parámetro mode especifica el tipo de credencial:

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

  • StsToken: Utiliza 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 OIDC, un token OIDC y un ARN de rol de RAM.

  • ChainableRamRoleArn: Utiliza el encadenamiento de roles para obtener una nueva credencial. Para ello, emplea una credencial inicial de profiles que se especifica con el parámetro source_profile.

4. Rol de RAM de una instancia ECS

Si no se encuentran credenciales de mayor prioridad, el SDK obtiene las credenciales del rol de RAM de la instancia ECS a través del servicio de metadatos en modo mejorado (IMDSv2). Este proceso requiere dos solicitudes; establezca ALIBABA_CLOUD_ECS_METADATA con el nombre del rol para reducirlo a una sola. Si IMDSv2 falla, el SDK vuelve al modo normal. Establezca ALIBABA_CLOUD_IMDSV1_DISABLE para controlar este comportamiento alternativo:

  1. Si se establece en false, el SDK vuelve al modo normal para recuperar las credenciales.

  2. Si se establece en true, solo se utiliza el modo mejorado y se lanza una excepción si ocurre un error.

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

Para deshabilitar el acceso a las credenciales desde los metadatos de ECS, establezca la variable de entorno ALIBABA_CLOUD_ECS_METADATA_DISABLED en 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á definida y apunta a un URI válido, la cadena accede al URI para recuperar un token de STS.

Cadena personalizada de proveedores de credenciales

Es posible anular el orden de búsqueda predeterminado mediante una cadena personalizada de proveedores de credenciales. También puede pasar un proveedor como cierre (closure).

<?php

use AlibabaCloud\Credentials\Providers\ChainProvider;

ChainProvider::set(
        ChainProvider::ini(),
        ChainProvider::env(),
        ChainProvider::instance()
);

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

La herramienta Credentials actualiza automáticamente las credenciales de sesión para los tipos ram_role_arn, ecs_ram_role, oidc_role_arn y credentials_uri. Las credenciales se almacenan en caché en la primera recuperación y se actualizan automáticamente cuando caducan.

Nota

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

Este ejemplo utiliza el patrón singleton para crear un cliente de credenciales, recupera credenciales en distintos intervalos y ejecuta una llamada a la API para comprobar su validez.

<?php

namespace Sample;

require_once 'vendor/autoload.php';

use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\Credentials\Credential\Config as CredentialConfig;
use AlibabaCloud\SDK\Ecs\V20140526\Ecs;
use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeRegionsRequest;
use Darabonba\OpenApi\Models\Config as OpenApiConfig;
use RuntimeException;

class Sample
{
    /**
     * @var Credential|null
     */
    private static $credentialInstance = null;

    /**
     * @return Credential
     * @throws RuntimeException
     */
    private static function getCredentialClient(): Credential
    {
        if (self::$credentialInstance === null) {
            try {
                $config = new CredentialConfig([
                    'type' => 'ram_role_arn',
                    'accessKeyId' => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
                    'accessKeySecret' => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
                    'roleArn' => getenv('ALIBABA_CLOUD_ROLE_ARN'),
                    'roleSessionName' => 'RamRoleArnTest',
                    'roleSessionExpiration' => 3600,
                ]);

                self::$credentialInstance = new Credential($config);
            } catch (\Exception $e) {
                throw new RuntimeException("Credential initialization failed: " . $e->getMessage(), 0, $e);
            }
        }

        return self::$credentialInstance;
    }

    /**
     * @var Ecs|null
     */
    private static $ecsClientInstance = null;

    /**
     * @return Ecs
     * @throws RuntimeException
     */
    private static function getEcsClient(): Ecs
    {
        if (self::$ecsClientInstance === null) {
            try {
                $config = new OpenApiConfig([
                    'credential' => self::getCredentialClient(),
                    'endpoint' => 'ecs.cn-hangzhou.aliyuncs.com'
                ]);

                self::$ecsClientInstance = new Ecs($config);
            } catch (\Exception $e) {
                throw new RuntimeException("ECS client initialization failed: " . $e->getMessage(), 0, $e);
            }
        }

        return self::$ecsClientInstance;
    }

    public static function main(): void
    {
        $task = function () {
            // Obtain and print the credential.
            $credentialClient = self::getCredentialClient();
            $credential = $credentialClient->getCredential();

            echo date('c') . PHP_EOL;
            echo "AK ID: {$credential->accessKeyId}" . PHP_EOL;
            echo "AK Secret: {$credential->accessKeySecret}" . PHP_EOL;
            echo "STS Token: {$credential->securityToken}" . PHP_EOL;

            // Call an ECS API operation to test whether the credential is valid.
            $ecsClient = self::getEcsClient();
            $request = new DescribeRegionsRequest();

            try {
                $response = $ecsClient->describeRegions($request);
                echo sprintf("Invoke result: %d" . PHP_EOL, $response->statusCode);
            } catch (\Exception $e) {
                throw new RuntimeException("ECS client execution failed: " . $e->getMessage(), 0, $e);
            }
        };

        call_user_func($task); // Immediately call the operation.

        sleep(600); // Call the operation after 600 seconds.
        call_user_func($task);

        sleep(3600); // Call the operation after 3,600 seconds.
        call_user_func($task);

        sleep(100); // Call the operation after 100 seconds.
        call_user_func($task);
    }
}

// Run the main function.
Sample::main();

image

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 utiliza la misma credencial que la primera, lo cual indica que se recuperó de la caché.

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

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

Documentos relacionados