All Products
Search
Document Center

Alibaba Cloud SDK:Manage access credentials

Last Updated:May 16, 2025

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

Background information

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

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

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

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

Prerequisites

  • PHP 5.6 or later is installed. We recommend that you install cURL 7.16.2 or later by using Transport Layer Security (TLS) and enable the cURL extension.

  • Alibaba Cloud SDK V2.0 is installed.

Install the Credentials tool

If you have globally installed Composer on your system, run the following command in your project directory to install Alibaba Cloud Credentials for PHP as a dependency:

composer require alibabacloud/credentials
  • We recommend that you use the latest version of Alibaba Cloud Credentials for PHP. This ensures that all credentials are supported.

  • View CHANGELOG.md to obtain a list of all released versions.

Initialize a Credentials client

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

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

  • We recommend that you build the Credentials client in single-instance mode. This mode not only enables the credential caching feature of the SDK, but also effectively prevents traffic control issues and waste of performance resources caused by multiple API calls.

Method 1: Use the default credential provider chain

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

<?php

use AlibabaCloud\Credentials\Credential;

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

// Do not specify a method to initialize a Credentials client.
$credClient = new Credential();

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

Call example

This example shows how to call the DescribeRegions operation of Elastic Compute Service (ECS). You must first install ECS SDK.

<?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 autoloading for Composer by using the autoload.php file in the vendor directory
require_once 'vendor/autoload.php';

// Use the default credential to initialize a Credentials client.
$credentialClient = new Credential();
$ecsConfig = new Config([
    // Use the credential to configure access credentials
    'credential' => $credentialClient,
    // Specify the endpoint of ECS.
    'endpoint' => 'ecs.aliyuncs.com'
]);
// Initialize the ECS SDK client.
$ecsClient = new Ecs($ecsConfig);
// Initialize the request.
$describeRegionsRequest = new DescribeRegionsRequest([]);
// Initialize the runtime configurations.
$runtime = new RuntimeOptions([]);
$resp = $ecsClient->describeRegionsWithOptions($describeRegionsRequest, $runtime);
// Return the status code.
echo $resp->statusCode;
// Obtain the response.
var_dump($resp);

Method 2: Use an AccessKey pair

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

Warning

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

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

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

Call example

You can use the Credentials tool to read an AccessKey pair and use the AccessKey pair as a credential to call the API operations of Alibaba Cloud services.

This example shows how to call the DescribeRegions operation of ECS. You must first install 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';

// Use an AccessKey pair to initialize a Credentials client.
$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([
    // Use the credential to configure access credentials
    'credential' => $credClient,
    // Specify the endpoint of ECS.
    'endpoint' => 'ecs.aliyuncs.com'
]);
// Initialize the ECS SDK client.
$ecsClient = new Ecs($ecsConfig);
// Initialize the request.
$describeRegionsRequest = new DescribeRegionsRequest([]);
// Initialize the runtime configurations.
$runtime = new RuntimeOptions([]);
$resp = $ecsClient->describeRegionsWithOptions($describeRegionsRequest, $runtime);
// Return the status code.
echo $resp->statusCode;
// Obtain the response.
var_dump($resp);

Method 3: Use a Security Token Service (STS) token

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

<?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' => 'sts',
    // 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'),
    // Obtain the STS token from the environment variable.
    'securityToken' => getenv('ALIBABA_CLOUD_SECURITY_TOKEN'),
]);
$credClient = new Credential($credConfig);

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

Call example

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

This example shows how to call the DescribeRegions operation of ECS. You must first install Elastic Compute Service SDK and Security Token Service 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 an STS token.
$config = new Config([
    // Obtain the AccessKey ID and AccessKey secret from environment variables. If the environment variables are not specified, specify them.
    '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([
    // Specify the ARN of the RAM role that you want your application to assume by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole.  
    'roleArn' => '<RoleArn>',
    // Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.  
    'roleSessionName' => '<RoleSessionName>',
]);
$assumeRoleResp = $stsClient->assumeRole($request);
$assumeRoleCredentials = $assumeRoleResp->body->credentials;

// Use an STS token to initialize a Credentials client.
$credentialConfig = new CredentialConfig([
    // The type of the credential.
    'type' => 'sts',
    'accessKeyId' => $assumeRoleCredentials->accessKeyId,
    'accessKeySecret' => $assumeRoleCredentials->accessKeySecret,
    'securityToken' => $assumeRoleCredentials->securityToken,
]);
$credentialClient = new Credential($credentialConfig);
$ecsConfig = new Config([
    // Use the credential to configure access credentials
    'credential' => $credentialClient,
    // Specify the endpoint of ECS.
    'endpoint' => 'ecs.aliyuncs.com'
]);// Initialize the ECS SDK client.
$ecsClient = new Ecs($ecsConfig);// Initialize the request.
$describeRegionsRequest = new DescribeRegionsRequest([]);// Initialize the runtime configurations.
$runtime = new RuntimeOptions([]);
$resp = $ecsClient->describeRegionsWithOptions($describeRegionsRequest, $runtime);// Return the status code.
echo $resp->statusCode;// Obtain the response.
var_dump($resp);

Method 4: Use an AccessKey pair and a RAM role

The underlying logic of this method is to use an STS token to configure access credentials. After you specify the Alibaba Cloud Resource Name (ARN) of a RAM role, the Credentials tool can obtain an STS token from STS. You can also limit the permissions of the RAM role by specifying a value for the policy parameter.

<?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' => 'ram_role_arn',
    'accessKeyId' => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    'accessKeySecret' => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    // Specify the ARN of the RAM role that you want your application to assume by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole.
    'roleArn' => '<RoleArn>',
    // Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
    'roleSessionName' => '<RoleSessionName>',
    // (Optional) Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    'policy' => '<Policy>',
    // Optional. Specify the validity period of the session. Unit: seconds. Default value: 3600.
    'roleSessionExpiration' => 3600,
]);
$credClient = new Credential($credConfig);

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

Call example

This example shows how to call the DescribeRegions operation of ECS. You must first install 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 to initialize a Credentials client.
$credentialConfig = new CredentialConfig([
    // The credential type.
    'type' => 'ram_role_arn',
    // Obtain the AccessKey ID from an environment variable.
    'accessKeyId' => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    // Obtain the AccessKey secret from an environment variable.
    'accessKeySecret' => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    // Specify the ARN of the RAM role that you want to assume by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole.
    'roleArn' => '<RoleArn>',
    // Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
    'roleSessionName' => '<RoleSessionName>',
    // Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}.
    'policy' => '<Policy>',
    // Optional. Specify the validity period of the session. Unit: seconds. Default value: 3600.
    'roleSessionExpiration' => 3600,
]);
$credentialClient = new Credential($credentialConfig);

$ecsConfig = new Config([
    // Use the credential to configure access credentials
    'credential' => $credentialClient,
    // Specify the endpoint of ECS.
    'endpoint' => 'ecs.aliyuncs.com'
]);
// Initialize the ECS SDK client.
$ecsClient = new Ecs($ecsConfig);
// Initialize the request.
$describeRegionsRequest = new DescribeRegionsRequest([]);
// Initialize the runtime configurations.
$runtime = new RuntimeOptions([]);
$resp = $ecsClient->describeRegionsWithOptions($describeRegionsRequest, $runtime);
// Return the status code.
echo $resp->statusCode;
// Obtain the response.
var_dump($resp);

Method 5: Use the RAM role of an ECS instance

ECS instances and elastic container instances can be assigned RAM roles. Programs that run on the instances can use the Credentials tool to automatically obtain an STS token for the RAM role. The STS token can be used to initialize the Credentials client.

By default, the Credentials tool accesses the metadata server of ECS in security hardening mode (IMDSv2). If an exception is thrown, the Credentials tool switches to the normal mode (IMDSv1). You can also set the disableIMDSv1 parameter or the ALIBABA_CLOUD_IMDSV1_DISABLE environment variable to specify how to handle exceptions:

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

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

Your instance configuration determines whether the instance metadata server supports IMDSv2.

You can also set the ALIBABA_CLOUD_ECS_METADATA_DISABLED=true environment variable to disable access to the metadata server of ECS.

Note
<?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. Specify the name of the RAM role of the ECS instance by specifying the ALIBABA_CLOUD_ECS_METADATA environment variable. If you do not specify this parameter, the value is automatically obtained. We recommend that you specify this parameter to reduce the number of requests.
    'roleName' => '<RoleName>',
    // Optional. Default value: false. true: The security hardening mode (IMDSv2) is forcibly used. false: The system preferentially attempts to obtain the access credential in security hardening mode. If the attempt fails, the system switches to normal mode (IMDSv1).
    // 'disableIMDSv1' => true,
]);
$credClient = new Credential($credConfig);

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

API call examples

<?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 the RAM role of an ECS instance to initialize a Credentials client.
$credConfig = new CredentialConfig([
    'type' => 'ecs_ram_role',
    // Optional. Specify the name of the RAM role of the ECS instance by specifying the ALIBABA_CLOUD_ECS_METADATA environment variable. If you do not specify this parameter, the value is automatically obtained. We recommend that you specify this parameter to reduce the number of requests.
    'roleName' => '<RoleName>',
]);
$credClient = new Credential($credConfig);

$ecsConfig = new Config([
    // Use the credential to configure access credentials
    'credential' => $credClient,
    // Specify the endpoint of ECS.
    'endpoint' => 'ecs.aliyuncs.com'
]);
// Initialize the ECS SDK client.
$ecsClient = new Ecs($ecsConfig);
// Initialize the request.
$describeRegionsRequest = new DescribeRegionsRequest([]);
// Initialize the runtime configurations.
$runtime = new RuntimeOptions([]);
$resp = $ecsClient->describeRegionsWithOptions($describeRegionsRequest, $runtime);
// Return the status code.
echo $resp->statusCode;
// Obtain the response.
var_dump($resp);

Method 6: Use the RAM role of an OIDC IdP

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

The following environment variables are injected into the pod:

ALIBABA_CLOUD_ROLE_ARN: the ARN of the RAM role.

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

ALIBABA_CLOUD_OIDC_TOKEN_FILE: the path of the OIDC token file.

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

// Use the RAM role of an OIDC identity provider (IdP) to initialize a Credentials client.
$credConfig = new CredentialConfig([
    // The type of the credential.
    'type' => 'oidc_role_arn',
    // Specify the ARN of the OIDC IdP by specifying the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
    'oidcProviderArn' => '<OidcProviderArn>',
    // Specify the path of the OIDC token file by specifying the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
    'oidcTokenFilePath' => '<OidcTokenFilePath>',
    // Specify the ARN of the RAM role that you want your application to assume by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole.
    'roleArn' => '<RoleArn>',
    // Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
    'roleSessionName' => '<RoleSessionName>',
    // Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    'policy' => '<Policy>',
    // Optional. Specify the validity period of the session.
    'roleSessionExpiration' => 3600,
]);

$credClient = new Credential($credConfig);

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

API call examples

This example shows how to call the DescribeRegions operation of ECS. You must first install 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 the RAM role of an OIDC IdP to initialize a Credentials client.
$credConfig = new CredentialConfig([
    // The credential type.
    'type' => 'oidc_role_arn',
    // Specify the ARN of the OIDC IdP by specifying the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
    'oidcProviderArn' => '<OidcProviderArn>',
    // Specify the path of the OIDC token file by specifying the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
    'oidcTokenFilePath' => '<OidcTokenFilePath>',
    // Specify the ARN of the RAM role that you want your application to assume by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole.
    'roleArn' => '<RoleArn>',
    // Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
    'roleSessionName' => '<RoleSessionName>',
    // Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    'policy' => '<Policy>',
    // Optional. Specify the validity period of the session.
    'roleSessionExpiration' => 3600,
]);

$credClient = new Credential($credConfig);

$ecsConfig = new Config([
    // Use the credential to configure access credentials
    'credential' => $credClient,
    // Specify the endpoint of ECS.
    'endpoint' => 'ecs.aliyuncs.com'
]);
// Initialize the ECS SDK client.
$ecsClient = new Ecs($ecsConfig);
// Initialize the request.
$describeRegionsRequest = new DescribeRegionsRequest([]);
// Initialize the runtime configurations.
$runtime = new RuntimeOptions([]);
$resp = $ecsClient->describeRegionsWithOptions($describeRegionsRequest, $runtime);
// Return the status code.
echo $resp->statusCode;
// Obtain the response.
var_dump($resp);

Method 7: Use a credential URI

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

<?php

namespace AlibabaCloud\SDK\Sample;

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

// Use a URI to initialize a Credentials client.
$credConfig = new Config([
    // The type of the credential.
    'type' => 'credentials_uri',
    // Obtain the URI of the credential in the http://local_or_remote_uri/ format by specifying the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
    'credentialsURI' => '<CredentialsUri>',
]);
$credClient = new Credential($credConfig);

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

The URI must meet the following requirements:

  • The URI supports GET requests.

  • The URI returns the HTTP status code 200.

  • The response body has the following structure:

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

API call examples

<?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 a URI to initialize a Credentials client.
$credConfig = new CredentialConfig([
    // The credential type.
    'type' => 'credentials_uri',
    // Obtain the URI of the credential in the http://local_or_remote_uri/ format by specifying the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
    'credentialsURI' => '<CredentialsUri>',
]);
$credClient = new Credential($credConfig);

$ecsConfig = new Config([
    // Use the credential to configure access credentials
    'credential' => $credClient,
    // Specify the endpoint of ECS.
    'endpoint' => 'ecs.aliyuncs.com'
]);
// Initialize the ECS SDK client.
$ecsClient = new Ecs($ecsConfig);
// Initialize the request.
$describeRegionsRequest = new DescribeRegionsRequest([]);
// Initialize the runtime configurations.
$runtime = new RuntimeOptions([]);
$resp = $ecsClient->describeRegionsWithOptions($describeRegionsRequest, $runtime);
// Return the status code.
echo $resp->statusCode;
// Obtain the response.
var_dump($resp);

Method 8: Use a bearer token

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

<?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' => 'bearer',
    // Enter the bearer token
    'bearerToken' => '<BearerToken>',
]);
$credClient = new Credential($credConfig);

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

Call example

This example shows how to call the GetInstance operation of Cloud Call Center. You must first install 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 a Credentials client.
$credConfig = new CredentialConfig([
    // The credential type.
    'type' => 'bearer',
    // Enter the bearer token
    'bearerToken' => '<BearerToken>',
]);
$credClient = new Credential($credConfig);

$config = new Config([
    // Use the credential to configure access credentials
    'credential' => $credClient,
    // Specify the endpoint of ECS.
    'endpoint' => 'ccc.cn-shanghai.aliyuncs.com'
]);
$cccClient = new CCC($config);
// Initialize the request.
$getInstanceRequest = new GetInstanceRequest([
    "instanceId" => "ccc-test"
]);
// Initialize the runtime configurations.
$runtime = new RuntimeOptions([]);
$resp = $cccClient->getInstanceWithOptions($getInstanceRequest, $runtime);
// Return the status code.
echo $resp->statusCode;
// Obtain the response.
var_dump($resp);

Default credential provider chain

If you want to use different types of credentials in the development and production environments of your application, you generally need to obtain the environment information from the code and write code branches to obtain different credentials for the development and production environments. The default credential provider chain of Alibaba Cloud Credentials for Java allows you to use the same code to obtain credentials for different environments based on configurations independent of the application. If you initialize a Credentials client without specifying a parameter by using $credential = new Credential();, Alibaba Cloud SDK searches for credentials in the following order.

1. Obtain the credential information from environment variables

If no credential information is found in the system attributes, the Credentials continues to check the environment variables.

  • If both the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are specified, they are used as the default credential.

  • If ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and ALIBABA_CLOUD_SECURITY_TOKEN are specified, the STS token is used as the default credential.

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

If no credentials with a higher priority are found, the Credentials tool checks the following environment variables that are related to the RAM role of the OIDC IdP:

  • ALIBABA_CLOUD_ROLE_ARN: the ARN of the RAM role.

  • ALIBABA_CLOUD_OIDC_PROVIDER_ARN: the ARN of the OIDC IdP.

  • ALIBABA_CLOUD_OIDC_TOKEN_FILE: the file path of the OIDC token.

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

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

If no credentials with a higher priority are found, the Credentials tool attempts to load the config.json file. Default file path:

  • Linux: ~/.aliyun/config.json

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

Do not change the preceding default paths. If you want to use this method to configure an access credential, manually create a config.json file in the corresponding path. Example:

{
	"current": "default",
	"profiles": [
		{
			"name": "default",
			"mode": "AK",
			"access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
			"access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>"
		},
		{
			"name":"client1",
			"mode":"RamRoleArn",
			"access_key_id":"<ALIBABA_CLOUD_ACCESS_KEY_ID>",
			"access_key_secret":"<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
			"ram_role_arn":"<ROLE_ARN>",
			"ram_session_name":"<ROLE_SESSION_NAME>",
			"expired_seconds":3600
		},
		{
			"name":"client2",
			"mode":"EcsRamRole",
			"ram_role_name":"<RAM_ROLE_ARN>"
		},
		{
			"name":"client3",
			"mode":"OIDC",
			"oidc_provider_arn":"<OIDC_PROVIDER_ARN>",
			"oidc_token_file":"<OIDC_TOKEN_FILE>",
			"ram_role_arn":"<ROLE_ARN>",
			"ram_session_name":"<ROLE_SESSION_NAME>",
			"expired_seconds":3600
		},
		{
			"name":"client4",
			"mode":"ChainableRamRoleArn",
			"source_profile":"<PROFILE_NAME>",
			"ram_role_arn":"<ROLE_ARN>",
			"ram_session_name":"<ROLE_SESSION_NAME>",
			"expired_seconds":3600
		}
	]
}

In the config.json file, you can use mode to specify a type of credential:

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

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

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

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

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

Note

Configure other parameters based on your business requirements.

After you complete the configurations, the Credentials tool selects the credential specified by the current parameter in the configuration file and initialize the client. You can also specify the ALIBABA_CLOUD_PROFILE environment variable to specify the credential information. For example, you can set the ALIBABA_CLOUD_PROFILE environment variable to client1.

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

If no credentials with a higher priority are found, the Credentials tool attempts to use the RAM role assigned to the ECS instance to obtain a credential. By default, the Credentials tool accesses the metadata server of ECS in security hardening mode (IMDSv2) to obtain the STS token of the RAM role used by the ECS instance and uses the STS token as the default credential. The Credentials tool automatically accesses the metadata server of ECS to obtain the name of the RAM role (RoleName) and then obtains the credential. Two requests are sent in this process. If you want to send only one request, add the ALIBABA_CLOUD_ECS_METADATA environment variable to specify the name of the RAM role. If an exception occurs in the security hardening mode (IMDSv2), the Credentials tool obtains the access credential in normal mode (IMDSv1). You can also configure the ALIBABA_CLOUD_IMDSV1_DISABLE environment variable to specify an exception handling logic. Valid values:

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

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

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

In addition, you can specify ALIBABA_CLOUD_ECS_METADATA_DISABLED=true to disable access from the Credentials tool to the metadata server of ECS.

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

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

5. Obtain the credential information based on a URI

If no valid credential is obtained by using the preceding methods, the Credentials tool checks the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. If this environment variable exists and specifies a valid URI, the Credentials tool initiates an HTTP requests to obtain an STS token as the default credential.

Custom credential provider chain

You can use a custom credential provider chain to search for credentials, or write a closure to pass the provider.

<?php

use AlibabaCloud\Credentials\Providers\ChainProvider;

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

Automatic update mechanism of session credentials

Session credentials include ARNs of RAM roles (RamRoleArn), RAM roles of ECS instances, RAM roles of OIDC IdPs (OIDCRoleArn), and credential URIs. The Credentials tool provides a built-in automatic update mechanism for session credentials. After a credential is obtained from the first call, the Credentials tool stores the credential in the cache. In subsequent calls, the credential is read from the cache as long as the credential is not expired. Otherwise, the Credentials tool makes a call to obtain the credential again, and updates the credential in the cache.

Note

For RAM roles of ECS instances, the Credentials tool updates the credential 15 minutes before the cache time-to-live (TTL) ends.

References