All Products
Search
Document Center

Alibaba Cloud SDK:Manage access credentials

Last Updated:Aug 06, 2024

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:

  1. 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.

  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.

  • 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
  1. We recommend that you use the latest version of Alibaba Cloud Credentials for PHP.

  2. 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

You can use the default credential provider chain to automatically create access credentials and call the API operations of Alibaba Cloud services without the need to use a hard-coded AccessKey pair.

The following sample code provides an example on how to call the DescribeRegions operation of Elastic Compute Service (ECS). Before you call this operation, you must install ECS SDK for PHP.

You can use the default credential provider chain to automatically create access credentials and call the API operations of Alibaba Cloud services without the need to use a hard-coded AccessKey pair. 
The following sample code provides an example on how to call the DescribeRegions operation of Elastic Compute Service (ECS). Before you call this operation, you must install ECS SDK for Java. 

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

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

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for PHP.

<?php

namespace AlibabaCloud\SDK\Sample;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\SDK\Ecs\V20140526\Ecs as Ecs;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeRegionsRequest;

// Enable autoloading for Composer by using the vendor/autoload.php file.
require_once('../vendor/autoload.php');
// Use an AccessKey pair to initialize a Credentials client. 
$credentialClient = new Credential([
    // Specify the type of the credential. 
    'type'              => 'access_key',
    // Specify the AccessKey ID. 
    'access_key_id'     => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    // Specify the AccessKey secret. 
    'access_key_secret' => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
]);
$ecsConfig = new Config([
    // Use the SDK Credentials package to configure a credential.
    '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);
// The status code.
echo $resp->statusCode;
// The response.
var_dump($resp);

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

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

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for PHP and STS SDK for PHP.

<?php

namespace AlibabaCloud\SDK\Sample;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\SDK\Ecs\V20140526\Ecs as Ecs;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeRegionsRequest;

// Enable autoloading for Composer by using the vendor/autoload.php file.
require_once('../vendor/autoload.php');
// Use an AccessKey pair to initialize a Credentials client. 
$credentialClient = new Credential([
    // Specify the type of the 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'     => getenv('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' => getenv('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'   => getenv('ALIBABA_CLOUD_SECURITY_TOKEN'),
]);
$ecsConfig = new Config([
    // Use the SDK Credentials package to configure a credential.
    '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);
// The status code.
echo $resp->statusCode;
// The response.
var_dump($resp);

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

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for PHP.

<?php

namespace AlibabaCloud\SDK\Sample;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\SDK\Ecs\V20140526\Ecs as Ecs;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeRegionsRequest;

// Enable autoloading for Composer by using the vendor/autoload.php file.
require_once('../vendor/autoload.php');
// Use an AccessKey pair to initialize a Credentials client. 
$credentialClient = new Credential([
    // Specify the type of the credential. 
    'type'              => 'ram_role_arn',
    // Specify the AccessKey ID. 
    'access_key_id'     => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    // Specify the AccessKey secret. 
    '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>',
]);
$ecsConfig = new Config([
    // Use the SDK Credentials package to configure a credential.
    '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);
// The status code.
echo $resp->statusCode;
// The response.
var_dump($resp);

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

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for PHP.

<?php

namespace AlibabaCloud\SDK\Sample;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\SDK\Ecs\V20140526\Ecs as Ecs;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeRegionsRequest;

// Enable autoloading for Composer by using the vendor/autoload.php file.
require_once('../vendor/autoload.php');
// Use an AccessKey pair to initialize a Credentials client. 
$credentialClient = new Credential([
    // Specify the type of the 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>',
]);
$ecsConfig = new Config([
    // Use the SDK Credentials package to configure a credential.
    '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);
// The status code.
echo $resp->statusCode;
// The response.
var_dump($resp);

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

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install Cloud Call Center SDK for PHP.

<?php

namespace AlibabaCloud\SDK\Sample;

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

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\CCC\V20200701\CCC;
use AlibabaCloud\SDK\CCC\V20200701\Models\GetInstanceRequest;

// Use an AccessKey pair to initialize a Credentials client. 
$credentialClient = new Credential([
    // Specify the type of the credential. 
    'type'         => 'bearer',
    // Enter the bearer token.
    'bearer_token' => '<BearerToken>',
]);
$config = new Config([
    // Use the SDK Credentials package to configure a credential.
    'credential'        => $credentialClient,
    // 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);
// The status code.
echo $resp->statusCode;
// 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 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:

  1. We recommend that you use the RAM role of an ECS instance or an STS token.

  2. We recommend that you use the default credential provider chain and record the credential information in environment variables or a configuration file.

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

References