Manage access credentials

更新时间:
复制 MD 格式

When you call API operations to manage cloud resources 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 how to configure different types of credentials and 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

A credential is a set of information that verifies a user's identity. To log on to a system, a user must provide valid credentials. Common credential types include:

  1. An AccessKey (AK), the permanent credential for an Alibaba Cloud account or a RAM user, is a key pair consisting of an AccessKey ID and an AccessKey Secret.

  2. An STS token is a temporary security credential for an Alibaba Cloud RAM role. You can customize its validity period and access permissions. For more information, see What is STS.

  3. A bearer token is a token type used for authentication and authorization.

Prerequisites

  • The credentials tool requires PHP 5.6 or later. We strongly recommend using the cURL extension and compiling cURL 7.16.2 or later with a TLS backend.

  • Alibaba Cloud SDK V2.0 is required.

Install credentials

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

composer require alibabacloud/credentials
  • Use the latest release of the dependency to ensure support for all credential types.

  • See CHANGELOG.md for a list of all released versions.

Credentials tool parameters

The configuration parameters for the Credentials tool are defined in AlibabaCloud\Credentials\Credential\Config. The credential type is specified by the required type parameter. After you specify the credential type, you must select the corresponding parameters. The following table describes the possible values for type and the parameters supported by each credential type. In the table, indicates a required parameter, - indicates an optional parameter, and × indicates an unsupported parameter.

Note

Do not use credential types or parameters that are not listed in the table.

Parameter

access_key

sts

ram_role_arn

ecs_ram_role

oidc_role_arn

credentials_uri

bearer

accessKeyId: The Access Key ID.

×

×

×

×

accessKeySecret: The Access Key secret.

×

×

×

×

securityToken: The Security Token Service (STS) token.

×

-

×

×

×

×

roleArn: The Alibaba Cloud Resource Name (ARN) of the RAM role.

×

×

×

×

×

roleSessionName: A custom session name. The default value is phpSdkRoleSessionName.

×

×

-

×

-

×

×

roleName: The name of the RAM role.

×

×

×

-

×

×

×

disableIMDSv1: Specifies whether to enforce security hardening mode. The default value is false.

×

×

×

-

×

×

×

bearerToken: The bearer token.

×

×

×

×

×

×

policy: A custom policy.

×

×

-

×

-

×

×

roleSessionExpiration: The session expiration time in seconds. The default value is 3600.

×

×

-

×

-

×

×

oidcProviderArn: The Alibaba Cloud Resource Name (ARN) of the OIDC identity provider.

×

×

×

×

×

×

oidcTokenFilePath: The file path of the OIDC token.

×

×

×

×

×

×

externalId: The external ID of the RAM role. This parameter prevents the confused deputy problem. For more information, see Use an external ID to prevent the confused deputy problem.

×

×

-

×

×

×

×

credentialsURI: The URI of the credential.

×

×

×

×

×

×

STSEndpoint: The endpoint for Security Token Service (STS). Both VPC and public endpoints are supported. For a list of valid values, see Endpoints. The default value is sts.aliyuncs.com.

×

×

-

×

-

×

×

timeout: The HTTP read timeout in milliseconds. The default value is 5000.

×

×

-

-

-

-

×

connectTimeout: The HTTP connection timeout in milliseconds. The default value is 10000.

×

×

-

-

-

-

×

Initialize a credentials client

You can use one of the following methods to initialize a Credentials client as needed:

Important
  • Storing an AccessKey in plaintext within a project is a security risk. If a code repository's permissions are misconfigured, the AccessKey can be exposed, compromising all resources in the account. Store your AccessKey in an environment variable or a configuration file instead.

  • When using the Credentials tool, use the singleton pattern. This enables the tool's built-in credential cache, which helps prevent throttling from frequent API calls and avoids wasting resources by creating multiple instances. For more information, see Automatic refresh mechanism for Session credentials.

Method 1: Using the default credential provider chain

graph TD A[Start] --> B{Check for environment variable}; B -->|Yes| C[Get credentials from environment variables]; B -->|No| D{Check for system property}; D -->|Yes| E[Get credentials from system properties]; D -->|No| F{Check for profile file}; F -->|Yes| G[Get credentials from profile file]; F -->|No| H{Check for instance RAM role}; H -->|Yes| I[Get instance RAM role]; H -->|No| J[Exception]; C --> K[End]; E --> K; G --> K; I --> K; J --> K;

A Credentials client initialized without parameters uses the default credential provider chain. See default credential provider chain to learn how it loads credentials.

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

API call example

This example shows how to call the DescribeRegions API of ECS. Before you begin, install the 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);

Method 2: Use an AccessKey

This method lets you create an AccessKey pair to initialize a Credentials client. For more information, see Create an AccessKey pair.

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

API example

This example demonstrates how to call the DescribeRegions operation and requires that you first install the 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);

Method 3: Use an STS token

This method lets you use a static STS token to initialize a Credentials client. For more information about how to obtain an STS token, see What is Security Token Service (STS)? The following example shows how to initialize a Credentials client 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;

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

API example

This example calls the DescribeRegions operation of ECS. First, install the ECS SDK and the 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);

Method 4: Using an AK and a RamRoleArn

Internally, this method uses an STS token. The credentials tool retrieves this token from STS by using the Alibaba Cloud Resource Name (ARN) of a RAM role. You can also assign a policy to limit the permissions of the resulting session.

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

API call example

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

Method 5: Use an ECS instance RAM role

You can attach an instance RAM role to both ECS and ECI instances. Applications running on these instances can then use the Credentials tool to automatically retrieve an STS token for the role and initialize a Credentials client.

By default, the Credentials tool first attempts to access the ECS metadata service in security hardening mode (IMDSv2). If this attempt fails, the tool falls back to normal mode to retrieve the access credential. You can customize this fallback behavior by setting the disableIMDSv1 parameter or the ALIBABA_CLOUD_IMDSV1_DISABLE environment variable:

  • If set to false (default), the tool falls back to normal mode on failure.

  • If set to true, the tool uses only security hardening mode and throws an exception on failure without falling back.

Your server-side configurations determine whether the server supports IMDSv2.

To disable credential access from ECS metadata, set the environment variable ALIBABA_CLOUD_ECS_METADATA_DISABLED=true.

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

API call

This example demonstrates how to call the DescribeRegions operation of ECS. You must install the ECS SDK to run this example.

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

Method 6: Use OIDCRoleArn

If you use the OIDC authentication protocol and have created a RAM role for an OIDC identity provider, pass the OIDC identity provider ARN, OIDC token, and RAM role ARN to the credentials tool. The tool automatically calls the AssumeRoleWithOIDC API to obtain an STS token for the RAM role and uses it as access credentials. These credentials support automatic refresh. For more information, see Automatic refresh mechanism for session credentials. For example, when your application runs in an ACK cluster with RRSA enabled, the credentials tool reads the OIDC configuration from the Pod environment variable and calls the AssumeRoleWithOIDC API to obtain an STS token for the service role. This allows your application to access Alibaba Cloud services.

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

API call example

This example demonstrates calling the DescribeRegions operation of ECS. Before you begin, install the 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);

Method 7: URI credential

By encapsulating an STS service and exposing its URI, external services can obtain an STS token. This method reduces the risk of exposing sensitive information, such as an AK. The credentials tool retrieves an STS token from the URI you provide and uses the token as access credentials. Credentials obtained this way support automatic refresh. For more information, see 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();

The URI must meet the following requirements:

  • Supports GET requests.

  • Returns a 200 status code.

  • The response body is a JSON object with the following fields:

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

API call

To use this example to call the DescribeRegions API of ECS, you must first install the 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);

Method 8: Use a bearer token

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

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

API example

This example shows how to call the GetInstance operation for Cloud Call Center (CCC). You must first install the 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);

Default credential provider chain

When your development and production environments use different types of credentials, you typically need to write conditional code to handle each environment. The default credential provider chain simplifies this, letting you use a single codebase and control credential retrieval through external configuration. When you initialize the credentials client by using $credential = new Credential(); without passing any parameters, the Alibaba Cloud SDK searches for credentials from the following sources in order:

1. 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. RAM role for 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. 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/macOS: ~/.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": "<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
		}
	]
}

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.

  • StsToken: uses the STS token as 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: utilizes a role chaining mechanism. It allows you to assume a new RAM role and acquire a new, temporary credential by referencing another credential profile, which is specified by the source_profile parameter.

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. ECS instance RAM role

If no higher-priority credentials are found, the SDK attempts to obtain credentials from the RAM role attached to the ECS instance. By default, the SDK accesses the ECS metadata service in enhanced mode (IMDSv2) to obtain an STS token for the ECS instance RAM role. This process involves two requests: the SDK first queries the metadata service to get the role name, and then retrieves the credentials. To reduce this to a single request, you can directly specify the instance RAM role name by setting the ALIBABA_CLOUD_ECS_METADATA environment variable. If an error occurs while using enhanced mode, the SDK falls back to normal mode. You can also set the ALIBABA_CLOUD_IMDSV1_DISABLE environment variable to control this fallback behavior:

  1. When set to false, the SDK falls back to normal mode to retrieve the credentials.

  2. When set to true, only enhanced mode is used, and an exception is thrown on failure.

Support for IMDSv2 depends on your server configuration.

To disable credential access from ECS metadata, set the ALIBABA_CLOUD_ECS_METADATA_DISABLED environment variable to true.

Note

5. Credentials URI

If no valid credential is obtained 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 override the default search order by using a custom credential provider chain. You can also pass a provider as a closure.

<?php

use AlibabaCloud\Credentials\Providers\ChainProvider;

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

Automatic refresh for session credentials

The Credentials tool provides a built-in automatic refresh mechanism for session credentials, including types such as ram_role_arn, ecs_ram_role, oidc_role_arn, and credentials_uri. When a credential client first obtains credentials, the Credentials tool caches them. For subsequent operations, the client retrieves the credentials from the cache. If the cached credentials expire, the client automatically fetches new credentials and updates the cache.

Note

For ecs_ram_role credentials, the Credentials tool proactively refreshes the credential 15 minutes before it expires.

This example creates a credential client using the singleton pattern. To demonstrate the automatic refresh mechanism, it retrieves credentials at different intervals and makes an OpenAPI call to verify their validity.

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

Log analysis:

  • In the first call, the system obtains the credential based on the configurations because the credential is not cached. After the system obtains the credential, the credential is stored in the cache.

  • The second call uses the same credential as the first call, which indicates that the credential is obtained from the cache.

  • In the third call, the credential has expired because the third call is 4,200 seconds later than the first call while the credential TTL (RoleSessionExpiration) is set to 3,600 seconds. The SDK obtains the credential again based on the automatic update mechanism and stored the credential in the cache.

  • The fourth call uses the same credential as the third call, which indicates that the credential is updated after cache expiration.

References