When you call API operations to manage cloud resources by using Alibaba Cloud SDKs, you must configure valid credential information. The Alibaba Cloud Credentials tool provides a powerful set of features that allow you to easily obtain and manage access credentials. This topic describes how to use the Credentials tool to configure various types of credentials such as the default credential, AccessKey pairs, or Security Token Service (STS) tokens. This topic also 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 your operations on cloud resources are efficient and secure.
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:
An AccessKey pair of an Alibaba Cloud account or a Resource Access Management (RAM) user. An AccessKey pair is permanently valid. It consists of an AccessKey ID and an AccessKey secret.
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?
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.
The in-house SDKs of services that use self-managed gateways are not installed.
Install the Credentials tool
If you have globally installed Composer in your system, run the following command in the directory of your project 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.
For information about all released versions of Alibaba Cloud Credentials for PHP, see CHANGELOG.md.
Initialize a Credentials client
You can use multiple methods to initialize a Credentials client. Use the type
parameter to specify a method to initialize a Credentials client.
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, see the Default credential provider chain section of this topic.
<?php
use AlibabaCloud\Credentials\Credential;
// Do not specify a method to initialize a Credentials client.
$credential = new Credential([]);
$credential->getAccessKeyId();
$credential->getAccessKeySecret();
Call example
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.
An Alibaba Cloud account has full access to all resources of 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 minimum necessary permissions to initialize a Credentials client.
<?php
use AlibabaCloud\Credentials\Credential;
$ak = new Credential([
'type' => 'access_key',
'access_key_id' => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
'access_key_secret' => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
]);
$ak->getAccessKeyId();
$ak->getAccessKeySecret();
Call example
Use an 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 sample code provides an example on how to initialize a Credentials client by using an STS token. The example does not show how to obtain an STS token.
{
"RequestId": "EA7A3526-F7DB-54A5-8300-9B742CFAA5EA",
"AssumedRoleUser": {
"Arn": "acs:ram::125499367423****:role/STStokenTestRole/STSsessionName",
"AssumedRoleId": "35219123109646****:STSsessionName"
},
"Credentials": {
"SecurityToken": "exampleToken",
"AccessKeyId": "STS.exampleAccessKeyID",
"AccessKeySecret": "exampleAccessKeySecret",
"Expiration": "2023-03-26T05:26:06Z"
}
}
<?php
use AlibabaCloud\Credentials\Credential;
$sts = new Credential([
'type' => 'sts',
// Replace <ALIBABA_CLOUD_ACCESS_KEY_ID> with the temporary AccessKey ID that is obtained from the response to the AssumeRole operation.
'access_key_id' => '<ALIBABA_CLOUD_ACCESS_KEY_ID>',
// Replace <ALIBABA_CLOUD_ACCESS_KEY_SECRET> with the temporary AccessKey secret that is obtained from the response to the AssumeRole operation.
'access_key_secret' => '<ALIBABA_CLOUD_ACCESS_KEY_SECRET>',
// Replace <ALIBABA_CLOUD_SECURITY_TOKEN> with the STS token that is obtained from the response to the AssumeRole operation.
'security_token' => '<ALIBABA_CLOUD_SECURITY_TOKEN>',
]);
$sts->getAccessKeyId();
$sts->getAccessKeySecret();
$sts->getSecurityToken();
Call example
Use an AccessKey pair and a RAM role
The underlying logic of this method is to use an STS token to initialize a Credentials client. 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 use the policy
parameter to limit the permissions of the RAM role.
<?php
use AlibabaCloud\Credentials\Credential;
$ramRoleArn = new Credential([
'type' => 'ram_role_arn',
'access_key_id' => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
'access_key_secret' => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
// Specify the ARN of the RAM role to be assumed. Example: acs:ram::123456789012****:role/adminrole.
'role_arn' => '<RoleArn>',
// Specify the name of the role session.
'role_session_name' => '<RoleSessionName>',
// Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}.
'policy' => '<Policy>',
]);
$ramRoleArn->getAccessKeyId();
$ramRoleArn->getAccessKeySecret();
$ramRoleArn->getRoleArn();
$ramRoleArn->getRoleSessionName();
$ramRoleArn->getPolicy();
Call example
Use the RAM role of an ECS instance
The underlying logic of this method is to use an STS token to initialize a Credentials client. The Credentials tool automatically obtains the RAM role attached to an ECS instance and uses the metadata server of ECS to obtain an STS token. The STS token is then used to initialize a Credentials client. You can also attach a RAM role to an elastic container instance or a worker node in an Alibaba Cloud Container Service for Kubernetes (ACK) cluster.
<?php
use AlibabaCloud\Credentials\Credential;
$ecsRamRole = new Credential([
'type' => 'ecs_ram_role',
// Optional. Specify the name of the RAM role of the ECS instance. If you do not specify this parameter, its value is automatically obtained. To reduce the number of requests, we recommend that you specify this parameter.
'role_name' => '<RoleName>',
]);
$ecsRamRole->getRoleName();
Call example
Use a bearer token
Only Cloud Call Center allows you to use a bearer token to initialize a Credentials client.
<?php
use AlibabaCloud\Credentials\Credential;
$bearerToken = new Credential([
'type' => 'bearer',
// Enter the bearer token.
'bearer_token' => '<BearerToken>',
]);
$bearerToken->getBearerToken();
$bearerToken->getSignature();
Call example
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 the Credentials tool allows you to use the same code to obtain credentials for different environments based on configurations independent of the application. If you use $credential = new Credential();
to initialize a Credentials client without specifying an initialization method, the Credentials tool obtains the credential information in the following order:
1. Obtain the credential information from environment variables
The Credentials tool first obtains the credential information from environment variables. If the ALIBABA_CLOUD_ACCESS_KEY_ID (AccessKey ID) and ALIBABA_CLOUD_ACCESS_KEY_SECRET (AccessKey secret) system environment variables are specified, the Credentials tool uses the specified AccessKey pair as the default credential.
2. Obtain the credential information from a configuration file
If no credentials are found in the previous step, the Credentials tool obtains the credential information from a configuration file. The path of the configuration file varies based on the operating system:
Linux: ~/.alibabacloud/credentials
Windows: C:\Users\USER_NAME\.alibabacloud\credentials
You can also specify the configuration file path by configuring the ALIBABA_CLOUD_CREDENTIALS_FILE environment variable. If the configuration file exists, the application initializes a Credentials client by using the credential information that is specified by default in the configuration file. You can also configure the ALIBABA_CLOUD_PROFILE environment variable to modify the default credential information that is read.
[default]
type = access_key
access_key_id = foo
access_key_secret = bar
[project1]
type = ecs_ram_role
role_name = EcsRamRoleTest
[project2]
type = ram_role_arn
access_key_id = foo
access_key_secret = bar
role_arn = role_arn
role_session_name = session_name
[project3]
type = rsa_key_pair
public_key_id = publicKeyId
private_key_file = /your/pk.pem
3. Obtain the credential information by using the RAM role of an ECS instance
If no credentials are found in the previous step, the Credentials tool obtains the value of the ALIBABA_CLOUD_ECS_METADATA environment variable that specifies the RAM role name of an ECS instance. If the RAM role exists, the application obtains an STS token of the RAM role as the default credential by using the metadata server of ECS.
Custom credential provider chain
You can use a custom credential provider chain to obtain credentials, or write a closure to pass the provider.
<?php
use AlibabaCloud\Credentials\Providers\ChainProvider;
ChainProvider::set(
ChainProvider::ini(),
ChainProvider::env(),
ChainProvider::instance()
);
Protect credential information
Credential leaks may expose the system to attacks. This is one of the main threats to cloud services. To prevent the leaks of plaintext credential information and reduce security risks, you can use the following solutions:
We recommend that you use the RAM role of an ECS instance or an STS token.
We recommend that you use the default credential provider chain and record the credential information in environment variables or a configuration file.
To use an explicit initialization method to initialize a Credentials client, we recommend that you use system properties or environment variables to record the credential information and obtain the credential information by using the
getenv
and$_ENV
methods.
<?php
use AlibabaCloud\Credentials\Credential;
$ak = new Credential([
'type' => 'access_key',
'access_key_id' => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
'access_key_secret' => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
]);
$ak->getAccessKeyId();
$ak->getAccessKeySecret();
Switch between credentials
You can use the following method to use different credentials to call different API operations in your application:
Use multiple Credentials clients
Initialize multiple Credentials clients to pass different credentials to different request clients.
<?php
use AlibabaCloud\Credentials\Credential;
$ak1 = new Credential([
'type' => 'access_key',
'access_key_id' => '<ALIBABA_CLOUD_ACCESS_KEY_ID>',
'access_key_secret' => '<ALIBABA_CLOUD_ACCESS_KEY_SECRET>',
]);
$ak1->getAccessKeyId();
$ak1->getAccessKeySecret();
$ak2 = new Credential([
'type' => 'access_key',
'access_key_id' => '<ALIBABA_CLOUD_ACCESS_KEY_ID>',
'access_key_secret' => '<ALIBABA_CLOUD_ACCESS_KEY_SECRET>',
]);
$ak2->getAccessKeyId();
$ak2->getAccessKeySecret();