The Alibaba Cloud SDK uses the Credentials tool to centrally manage credentials, such as your AccessKey and STS Token. This topic describes the supported credential types and their configuration methods.
Background
Credentials verify a user's identity when accessing a system. Common types include:
-
An AccessKey pair (AK) is a permanent credential for an Alibaba Cloud account or RAM user, consisting of an AccessKey ID and an AccessKey Secret.
-
An STS token is a temporary security credential for an Alibaba Cloud RAM role with customizable validity and permissions. What is STS.
-
A bearer token is used for authentication and authorization.
Prerequisites
-
PHP 5.6 or later is required. The cURL extension with cURL 7.16.2+ and a TLS backend is strongly recommended.
-
Alibaba Cloud SDK V2.0 is required.
Install credentials
With Composer installed globally, run this command to add Alibaba Cloud Credentials for PHP:
composer require alibabacloud/credentials
-
Use the latest version to ensure all credential types are supported.
-
All released versions are listed in the CHANGELOG.
Credential parameters
Configuration parameters are defined in AlibabaCloud\Credentials\Credential\Config. Set the required type parameter to specify the credential type, then configure the corresponding parameters. The following table lists type values and supported parameters, where √ = required, - = optional, × = unsupported.
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 |
× |
× |
- |
× |
- |
× |
× |
|
roleName: The name of the RAM role. |
× |
× |
× |
- |
× |
× |
× |
|
disableIMDSv1: Specifies whether to enforce security hardening mode. The default value is |
× |
× |
× |
- |
× |
× |
× |
|
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, used to prevent the confused deputy problem. |
× |
× |
- |
× |
× |
× |
× |
|
credentialsURI: The URI of the credential. |
× |
× |
× |
× |
× |
√ |
× |
|
STSEndpoint: The STS endpoint. Both VPC and public endpoints are supported. Valid values: Endpoints. Default: |
× |
× |
- |
× |
- |
× |
× |
|
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
The previous section describes the credential types and configuration parameters supported by the Credentials tool. The following sections provide code examples showing how to use the tool. Select the method that best fits your scenario.
-
Storing an AccessKey in plaintext is a security risk. If a repository is misconfigured, the AccessKey can be exposed, compromising all resources in the account. Store AccessKeys in environment variables or configuration files.
-
Use the singleton pattern with the Credentials tool. This enables the built-in credential cache, preventing throttling from frequent API calls and avoids wasting resources by creating multiple instances. Automatic refresh mechanism for Session credentials.
Method 1: Using the default credential provider chain
A Credentials client initialized without parameters uses the default credential provider chain.
<?php
use AlibabaCloud\Credentials\Credential;
// Use the Composer autoloader by requiring the autoload.php file from the vendor directory.
require_once 'vendor/autoload.php';
// No parameters specified.
$credClient = new Credential();
$credential = $credClient->getCredential();
$credential->getAccessKeyId();
$credential->getAccessKeySecret();
API call example
Method 2: Use an AccessKey
The Credentials tool uses the AccessKey you provide as the access credential.
An Alibaba Cloud account (root account) has full permissions over all its resources, so an exposed AK poses a significant security risk. Do not use the AK of a root account.
Use the AK of a RAM user with least-privilege permissions.
<?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
Method 3: Use an STS token
The Credentials tool uses the static STS token you provide as the access credential.
<?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
Method 4: Use an AccessKey and RAM role ARN
This method obtains an STS token by assuming a RAM role. You can assign a policy to limit the session permissions.
<?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
Method 5: Use an ECS instance RAM role
Attach an instance RAM role to ECS or ECI instances. Applications on these instances can use the Credentials tool to obtain an STS token automatically.
By default, the Credentials tool accesses the ECS metadata service in security hardening mode (IMDSv2), falling back to normal mode on failure. Control this with the disableIMDSv1 parameter or the ALIBABA_CLOUD_IMDSV1_DISABLE environment variable:
-
If set to false (default), the tool falls back to normal mode.
-
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.
-
Obtaining a temporary credential in security hardening mode requires Credentials version 1.2.0 or later.
-
ECS instance metadata: Obtain instance metadata.
-
Assign a RAM role to an ECS or ECI instance: Instance RAM roles, Use an instance RAM role by calling API operations.
<?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
Method 6: Use an OIDC role ARN
After creating a RAM role for an OIDC identity provider, pass the OIDC provider ARN, OIDC token, and RAM role ARN to the Credentials tool. The tool calls AssumeRoleWithOIDC to obtain an STS token, with Automatic refresh mechanism for session credentials. For example, in an ACK cluster with RRSA enabled, the tool reads the OIDC configuration from Pod environment variables and obtains an STS token for the service role.
<?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
Method 7: Use a URI credential
Wrap an STS service behind a URI to avoid exposing AccessKeys. The Credentials tool retrieves an STS token from the URI and refreshes it automatically. 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
Method 8: Use a bearer token
Currently, only Alibaba Cloud Call Center (CCC) supports bearer token authentication.
<?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
Default credential provider chain
The default credential provider chain lets you use a single codebase across environments by controlling credential retrieval through external configuration. When initialized without parameters using $credential = new Credential();, the SDK searches for credentials in this order:
1. Environment variables
If no credential is found in the system properties, the provider chain then checks for environment variables.
-
If both ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are present and not empty, the provider chain uses them as the default credential.
-
If ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and ALIBABA_CLOUD_SECURITY_TOKEN are also set, the provider chain uses an STS token as the default credential.
2. RAM role for an OIDC IdP
If no credential has been found, the provider chain checks for the following environment variables related to an OIDC RAM role:
-
ALIBABA_CLOUD_ROLE_ARN: The ARN of the RAM role.
-
ALIBABA_CLOUD_OIDC_PROVIDER_ARN: The ARN of the OIDC provider.
-
ALIBABA_CLOUD_OIDC_TOKEN_FILE: The file path of the OIDC token.
If all three environment variables are present and not empty, the provider chain uses these values to call the AssumeRoleWithOIDC API of the Security Token Service (STS) to obtain an STS token.
3. config.json file
If no credential has been found, the provider chain attempts to load the shared credentials file, config.json, from its default location and uses the credential specified in the file.
-
Linux/macOS:
~/.aliyun/config.json -
Windows:
C:\Users\USER_NAME\.aliyun\config.json
To configure a credential this way, you can use the Alibaba Cloud CLI or manually create a config.json file in the appropriate path. The following example shows the content format:
{
"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
}
]
}
|
Parameter |
Description |
|
current |
Specify the credential name to retrieve the corresponding credential configuration. The credential name is the value of the |
|
profiles |
Contains a collection of credential configurations. The
|
4. ECS instance RAM role
If no higher-priority credentials are found, the SDK obtains credentials from the ECS instance RAM role via the metadata service in enhanced mode (IMDSv2). This involves two requests; set ALIBABA_CLOUD_ECS_METADATA to the role name to reduce it to one. On IMDSv2 failure, the SDK falls back to normal mode. Set ALIBABA_CLOUD_IMDSV1_DISABLE to control this fallback:
-
When set to
false, the SDK falls back to normal mode to retrieve the credentials. -
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.
-
ECS instance metadata: Instance metadata.
-
Attach a RAM role to an ECS or ECI instance: Create a RAM role, Grant an instance RAM role to an ECI instance.
5. Credentials URI
If no credential has been found, the provider chain checks for the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. If this variable is set and points to a valid URI, the chain accesses the URI to retrieve an STS token.
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 automatically refreshes session credentials for ram_role_arn, ecs_ram_role, oidc_role_arn, and credentials_uri types. Credentials are cached on first retrieval and refreshed automatically when they expire.
For ecs_ram_role credentials, the Credentials tool proactively refreshes the credential 15 minutes before it expires.
This example uses the singleton pattern to create a credential client, retrieves credentials at different intervals, and makes an API call to verify 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();

Analysis based on the log output:
-
On the first call, the cache is empty. The system retrieves a credential based on your configuration and then stores it in the cache.
-
The second call uses the same credential as the first, indicating it was retrieved from the cache.
-
On the third call, the cached credential has expired. Its expiration time (
RoleSessionExpiration) is 3,600 seconds, but this call is made 4,200 seconds after the first one. Consequently, the SDK's automatic refresh mechanism fetches a new credential and updates the cache. -
The fourth call uses the same credential as the third, confirming that the cache was updated.
Related documents
-
For an overview of the basic concepts of RAM, see Basic concepts.
-
To create an AccessKey, see Create an AccessKey.
-
To programmatically create RAM users, AccessKeys, and RAM roles; define permission policies; and grant permissions, see RAM SDK overview.
-
To programmatically assume a role, see STS SDK overview.
-
For details about the RAM and STS APIs, see the API reference.
-
Best practices for using access credentials to call Alibaba Cloud OpenAPI