Todos os produtos
Search
Central de documentação

Alibaba Cloud SDK:Gerenciar credenciais de acesso

Última atualização: Jun 28, 2026

O Alibaba Cloud SDK usa a ferramenta Credentials para gerenciar credenciais centralmente, como AccessKey e STS Token. Este tópico descreve os tipos de credenciais compatíveis e seus métodos de configuração.

Contexto

Credenciais verificam a identidade do usuário no acesso ao sistema. Os tipos mais comuns incluem:

  1. Par de AccessKey (AK): credencial permanente para conta Alibaba Cloud ou usuário RAM, composta por AccessKey ID e AccessKey Secret.

  2. Token STS: credencial de segurança temporária para função RAM do Alibaba Cloud, com validade e permissões personalizáveis. O que é STS.

  3. Bearer token: usado para autenticação e autorização.

Pré-requisitos

  • PHP 5.6 ou superior. Recomenda-se fortemente a extensão cURL com cURL 7.16.2+ e backend TLS.

  • Alibaba Cloud SDK V2.0.

Instalar credentials

Com o Composer instalado globalmente, execute este comando para adicionar o Alibaba Cloud Credentials para PHP:

composer require alibabacloud/credentials
  • Use a versão mais recente para garantir suporte a todos os tipos de credenciais.

  • Todas as versões lançadas constam no CHANGELOG.

Parâmetros de credenciais

Defina os parâmetros de configuração em AlibabaCloud\Credentials\Credential\Config. Especifique o parâmetro obrigatório type para indicar o tipo de credencial e configure os parâmetros correspondentes. A tabela a seguir lista os valores de type e os parâmetros compatíveis, onde = obrigatório, - = opcional, × = não compatível.

Nota

Não use tipos de credenciais ou parâmetros fora da tabela.

Parâmetro

access_key

sts

ram_role_arn

ecs_ram_role

oidc_role_arn

credentials_uri

bearer

accessKeyId: O Access Key ID.

×

×

×

×

accessKeySecret: O segredo do Access Key.

×

×

×

×

securityToken: O token do Security Token Service (STS).

×

-

×

×

×

×

roleArn: O Alibaba Cloud Resource Name (ARN) da função RAM.

×

×

×

×

×

roleSessionName: Nome de sessão personalizado. Valor padrão: phpSdkRoleSessionName.

×

×

-

×

-

×

×

roleName: Nome da função RAM.

×

×

×

-

×

×

×

disableIMDSv1: Define se o modo de reforço de segurança deve ser imposto. Valor padrão: false.

×

×

×

-

×

×

×

bearerToken: O bearer token.

×

×

×

×

×

×

policy: Política personalizada.

×

×

-

×

-

×

×

roleSessionExpiration: Tempo de expiração da sessão em segundos. Valor padrão: 3600.

×

×

-

×

-

×

×

oidcProviderArn: Alibaba Cloud Resource Name (ARN) do provedor de identidade OIDC.

×

×

×

×

×

×

oidcTokenFilePath: Caminho do arquivo do token OIDC.

×

×

×

×

×

×

externalId: ID externo da função RAM, usado para evitar o problema de deputado confuso.

×

×

-

×

×

×

×

credentialsURI: URI da credencial.

×

×

×

×

×

×

STSEndpoint: Endpoint do STS. Endpoints VPC e públicos são compatíveis. Valores válidos: Endpoints. Padrão: sts.aliyuncs.com.

×

×

-

×

-

×

×

timeout: Tempo limite de leitura HTTP em milissegundos. Valor padrão: 5000.

×

×

-

-

-

-

×

connectTimeout: Tempo limite de conexão HTTP em milissegundos. Valor padrão: 10000.

×

×

-

-

-

-

×

Inicializar um cliente de credenciais

A seção anterior descreveu os tipos de credenciais e parâmetros de configuração compatíveis com a ferramenta Credentials. As seções seguintes apresentam exemplos de código sobre como usar a ferramenta. Selecione o método mais adequado ao seu cenário.

Importante
  • Armazenar AccessKey em texto simples representa risco de segurança. Repositórios mal configurados podem expor o AccessKey e comprometer todos os recursos da conta. Armazene AccessKeys em variáveis de ambiente ou arquivos de configuração.

  • Adote o padrão singleton com a ferramenta Credentials. Isso ativa o cache interno de credenciais, evita limitações por chamadas frequentes à API e previne desperdício de recursos com múltiplas instâncias. Mecanismo de atualização automática para credenciais de sessão.

Método 1: Usar a cadeia de provedores de credenciais padrão

Clientes Credentials inicializados sem parâmetros usam a cadeia de provedores de credenciais padrão.

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

Exemplo de chamada de API

Este exemplo chama a API DescribeRegions do ECS. Antes de começar, instale o ECS SDK for 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 um AccessKey

A ferramenta Credentials usa o AccessKey fornecido como credencial de acesso.

Aviso

Contas Alibaba Cloud (conta raiz) têm permissões totais sobre todos os recursos. Um AK exposto representa risco significativo de segurança. Não use o AK da conta raiz.

Use o AK de um usuário RAM com permissões de privilégio mínimo.

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

Exemplo de API

Este exemplo demonstra como chamar a operação DescribeRegions. Instale primeiro o ECS SDK.

<?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 um token STS

A ferramenta Credentials usa o token STS estático fornecido como credencial de acesso.

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

Exemplo de API

Este exemplo chama a operação DescribeRegions do ECS. Primeiro, instale o ECS SDK e o STS SDK.

<?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 um AccessKey e ARN de função RAM

Este método obtém um token STS ao assumir uma função RAM. É possível atribuir uma policy para limitar as permissões da sessão.

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

Exemplo de chamada de API

Este exemplo chama a operação DescribeRegions do ECS. Instale primeiro o ECS SDK.

<?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 uma função RAM de instância ECS

Anexe uma função RAM de instância a instâncias ECS ou ECI. Aplicações nessas instâncias podem usar a ferramenta Credentials para obter tokens STS automaticamente.

Por padrão, a ferramenta Credentials acessa o serviço de metadados do ECS no modo de reforço de segurança (IMDSv2) e reverte para o modo normal em caso de falha. Controle esse comportamento com o parâmetro disableIMDSv1 ou a variável de ambiente ALIBABA_CLOUD_IMDSV1_DISABLE:

  • Se definido como false (padrão), a ferramenta reverte para o modo normal.

  • Se definido como true, a ferramenta usa apenas o modo de reforço de segurança e lança exceção em caso de falha, sem reverter.

As configurações do servidor determinam a compatibilidade com IMDSv2.

Para desativar o acesso a credenciais via metadados do ECS, defina a variável de ambiente 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();

Chamada de API

Este exemplo demonstra como chamar a operação DescribeRegions do ECS. Instale o ECS SDK para executar este exemplo.

<?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 um ARN de função OIDC

Após criar uma função RAM para provedor de identidade OIDC, passe o ARN do provedor OIDC, o token OIDC e o ARN da função RAM para a ferramenta Credentials. A ferramenta chama AssumeRoleWithOIDC para obter um token STS, com atualização automática para credenciais de sessão. Por exemplo, em cluster ACK com RRSA ativado, a ferramenta lê a configuração OIDC das variáveis de ambiente do Pod e obtém token STS para a função de serviço.

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

Exemplo de chamada de API

Este exemplo chama a operação DescribeRegions do ECS. Antes de começar, instale o ECS SDK for 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 uma credencial URI

Encapsule um serviço STS em uma URI para evitar exposição de AccessKeys. A ferramenta Credentials recupera tokens STS da URI e os atualiza automaticamente. Consulte Atualização automática para credenciais do tipo sessão.

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

A URI deve atender aos seguintes requisitos:

  • Compatibilidade com requisições GET.

  • Retorno de código de status 200.

  • Corpo da resposta em formato JSON com os seguintes campos:

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

Chamada de API

Para chamar a API DescribeRegions do ECS com este exemplo, instale primeiro o ECS SDK.

<?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 um bearer token

Atualmente, apenas o Alibaba Cloud Call Center (CCC) oferece suporte a autenticação via 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();

Exemplo de API

Este exemplo chama a operação GetInstance do Cloud Call Center (CCC). Instale primeiro o CCC SDK.

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

Cadeia de provedores de credenciais padrão

A cadeia de provedores de credenciais padrão permite usar uma única base de código em diferentes ambientes, controlando a recuperação de credenciais via configuração externa. Ao inicializar sem parâmetros com $credential = new Credential();, o SDK busca credenciais nesta ordem:

1. Variáveis de ambiente

Se nenhuma credencial for encontrada nas propriedades do sistema, a cadeia de provedores verifica as variáveis de ambiente.

  • Se ALIBABA_CLOUD_ACCESS_KEY_ID e ALIBABA_CLOUD_ACCESS_KEY_SECRET estiverem presentes e não vazios, a cadeia de provedores os usa como credencial padrão.

  • Se ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET e ALIBABA_CLOUD_SECURITY_TOKEN também estiverem definidos, a cadeia de provedores usa token STS como credencial padrão.

2. Função RAM para IdP OIDC

Caso nenhuma credencial seja encontrada, a cadeia de provedores verifica as seguintes variáveis de ambiente relacionadas a função RAM OIDC:

  • ALIBABA_CLOUD_ROLE_ARN: ARN da função RAM.

  • ALIBABA_CLOUD_OIDC_PROVIDER_ARN: ARN do provedor OIDC.

  • ALIBABA_CLOUD_OIDC_TOKEN_FILE: Caminho do arquivo do token OIDC.

Se todas as três variáveis de ambiente estiverem presentes e não vazias, a cadeia de provedores usa esses valores para chamar a API AssumeRoleWithOIDC do Security Token Service (STS) e obter um token STS.

3. Arquivo config.json

Se nenhuma credencial for encontrada, a cadeia de provedores tenta carregar o arquivo de credenciais compartilhadas config.json da localização padrão e usa a credencial especificada no arquivo.

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

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

Para configurar credenciais dessa forma, use a Alibaba Cloud CLI ou crie manualmente um arquivo config.json no caminho apropriado. O exemplo a seguir mostra o formato do conteúdo:

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

Descrição

current

Especifique o nome da credencial para recuperar a configuração correspondente. O nome da credencial corresponde ao valor do parâmetro name em profiles. Por padrão, o sistema prioriza o nome da credencial definido pela variável de ambiente ALIBABA_CLOUD_PROFILE. Se essa variável não estiver configurada, o sistema usa o nome especificado em current.

profiles

Coleção de configurações de credenciais. O parâmetro mode especifica o tipo de credencial:

  • AK: Usa AccessKey de usuário RAM como credencial.

  • StsToken: Usa token STS como credencial.

  • RamRoleArn: Assume função RAM usando credenciais de usuário RAM para obter credencial temporária.

  • EcsRamRole: Obtém credencial dos metadados da instância.

  • OIDC: Obtém credencial usando ARN de provedor OIDC, token OIDC e ARN de função RAM.

  • ChainableRamRoleArn: Usa encadeamento de funções para obter nova credencial, utilizando credencial inicial de profiles especificada pelo parâmetro source_profile.

4. Função RAM de instância ECS

Se nenhuma credencial de maior prioridade for encontrada, o SDK obtém credenciais da função RAM da instância ECS via serviço de metadados no modo aprimorado (IMDSv2). Esse processo envolve duas requisições. Defina ALIBABA_CLOUD_ECS_METADATA com o nome da função para reduzir para apenas uma requisição. Em caso de falha no IMDSv2, o SDK reverte para o modo normal. Configure ALIBABA_CLOUD_IMDSV1_DISABLE para controlar essa reversão:

  1. Quando definido como false, o SDK reverte para o modo normal para recuperar credenciais.

  2. Quando definido como true, apenas o modo aprimorado é usado e uma exceção é lançada em caso de falha.

A compatibilidade com IMDSv2 depende da configuração do servidor.

Para desativar o acesso a credenciais via metadados do ECS, defina a variável de ambiente ALIBABA_CLOUD_ECS_METADATA_DISABLED como true.

Nota

5. URI de Credenciais

Se nenhuma credencial for encontrada, a cadeia de provedores verifica a variável de ambiente ALIBABA_CLOUD_CREDENTIALS_URI. Se esta variável estiver definida e apontar para URI válida, a cadeia acessa a URI para recuperar token STS.

Cadeia de provedores de credenciais personalizada

Substitua a ordem de busca padrão usando uma cadeia de provedores de credenciais personalizada. Também é possível passar um provedor como closure.

<?php

use AlibabaCloud\Credentials\Providers\ChainProvider;

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

Atualização automática para credenciais de sessão

A ferramenta Credentials atualiza automaticamente credenciais de sessão para os tipos ram_role_arn, ecs_ram_role, oidc_role_arn e credentials_uri. As credenciais são armazenadas em cache na primeira recuperação e atualizadas automaticamente ao expirar.

Nota

Para credenciais ecs_ram_role, a ferramenta Credentials atualiza proativamente a credencial 15 minutos antes da expiração.

Este exemplo usa o padrão singleton para criar cliente de credenciais, recupera credenciais em intervalos diferentes e faz chamada de API para verificar validade.

<?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álise baseada na saída do log:

  • Na primeira chamada, o cache está vazio. O sistema recupera credencial conforme configuração e a armazena no cache.

  • A segunda chamada usa a mesma credencial da primeira, indicando recuperação do cache.

  • Na terceira chamada, a credencial em cache expirou. O tempo de expiração (RoleSessionExpiration) é de 3.600 segundos, mas esta chamada ocorre 4.200 segundos após a primeira. Consequentemente, o mecanismo de atualização automática do SDK busca nova credencial e atualiza o cache.

  • A quarta chamada usa a mesma credencial da terceira, confirmando atualização do cache.

Documentos relacionados