To use Object Storage Service (OSS) SDK for PHP to initiate a request, you must configure access credentials. Alibaba Cloud services use access credentials to verify identity information and access permissions. You can select different types of access credentials based on authentication and authorization requirements in different scenarios.
Notes
For a list of OSS regions and endpoints, see Regions and endpoints.
If you want to create an AccessKey pair for a RAM user, see Create an AccessKey pair.
Before you configure access credentials, make sure that the latest version of OSS SDK for PHP is installed. For more information, see Installation.
Configuration examples for common scenarios
Use the AccessKey pair of a RAM user
Assume that your application requires long-term access to OSS without frequently rotating access credentials and runs in a secure and stable environment that is not vulnerable to external attacks. In this case, you can use an AccessKey pair (an AccessKey ID and an AccessKey secret) of your Alibaba Cloud account or a RAM user to initialize a credential provider. Take note that this method requires you to manually maintain an AccessKey pair. This poses security risks and increases maintenance complexity.
An Alibaba Cloud account has full permissions on its resources, and leaks of its AccessKey pair pose significant security risks. Therefore, we recommend that you use the AccessKey pair of a RAM user with the minimum required permissions to initialize a credential provider.
For information about how to create an AccessKey pair for a RAM user, see Create an AccessKey pair for a RAM user. You can record the AccessKey secret of a RAM user only when you create the RAM user. If you forget the AccesKey secret, you can create a new AccessKey pair for credential rotation.
Environment variables
Configure environment variables for the AccessKey pair.
Linux
Run the following commands on the CLI to add the configurations of the environment variables to the
~/.bashrc
file:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
Run the following command to apply the changes:
source ~/.bashrc
Run the following commands to check whether the environment variables have taken effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
Run the following command in the terminal to view the default shell type:
echo $SHELL
Configure environment variables based on the default shell type.
Zsh
Run the following commands to add the configurations of the environment variables to the
~/.zshrc
file:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
Run the following command to apply the changes:
source ~/.zshrc
Run the following commands to check whether the environment variables take effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
Run the following commands to add the configurations of the environment variables to the
~/.bash_profile
file:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
Run the following command to apply the changes:
source ~/.bash_profile
Run the following commands to check whether the environment variables take effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Windows
CMD
Run the following commands in CMD:
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
Run the following commands to check whether the environment variables take effect:
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
Run the following commands in PowerShell:
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
Run the following commands to check whether the environment variable takes effect:
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
To make sure that your settings are loaded, restart or refresh your compilation and runtime environments, such as the IDE, command-line tool, desktop applications, and services in the background.
Pass the credentials by using environment variables.
<?php // Include the autoload file to load dependencies. require_once __DIR__ . '/../vendor/autoload.php'; use AlibabaCloud\Oss\V2 as Oss; # Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. $region = "cn-hangzhou"; // Use EnvironmentVariableCredentialsProvider to retrieve the AccessKey ID and AccessKey secret from environment variables. $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Use the default configuration of the SDK. $cfg = Oss\Config::loadDefault(); $cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider. $cfg->setRegion($region); // Specify the region in which the bucket is located. // Create an OSSClient instance. $client = new Oss\Client($cfg); // Use the OSSClient instance to perform subsequent operations.
Static credentials
The following example shows how to hardcode access credentials of a RAM user in code:
Do not embed access credentials in application code deployed in a production environment. This method is intended only for testing.
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
# Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
$region = "cn-hangzhou";
# Create a static credential provider and explicitly specify the AccessKey ID and AccessKey secret of your RAM user.
$credentialsProvider = new Oss\Credentials\StaticCredentialsProvider("RAM AccessKey ID","RAM AccessKey Secret");
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Use the OSSClient instance to perform subsequent operations.
Use temporary access credentials provided by STS
If your application needs to access OSS temporarily, you can use temporary access credentials provided by STS, which consist of an AccessKey pair and an STS token. Take note that this method requires you to manually maintain an STS token. This poses security risks and increases maintenance complexity. If you want to prolong access after the existing STS token expires, you need to manually refresh the STS token.
You can obtain temporary access credentials by calling the AssumeRole operation. For more information, see AssumeRole.
You can also obtain temporary access credentials by using the SDK. For more information, see Use temporary access credentials provided by STS to access OSS.
You must specify a validity period for the STS token when you generate the token. An expired STS token cannot be used.
For a list of STS endpoints, see Endpoints.
Environment variables
Configure environment variables for temporary access credentials.
Mac OS X/Linux/Unix
WarningThis example uses the temporary access credentials (AccessKey ID, AccessKey secret, and STS token) provided by STS instead of the AccessKey ID and AccessKey secret of a RAM user.
An AccessKey ID provided by STS begins with STS, as demonstrated in the example 'STS.****************'.
export OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID> export OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET> export OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>
Windows
WarningThis example uses the temporary access credentials (AccessKey ID, AccessKey secret, and STS token) provided by STS instead of the AccessKey pair (AccessKey ID and AccessKey secret) of a RAM user.
An AccessKey ID provided by STS begins with STS, as demonstrated in the example 'STS.****************'.
set OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID> set OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET> set OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>
Pass the credentials by using environment variables.
<?php // Include the autoload file to load dependencies. require_once __DIR__ . '/../vendor/autoload.php'; use AlibabaCloud\Oss\V2 as Oss; # Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. $region = "cn-hangzhou"; // Use EnvironmentVariableCredentialsProvider to retrieve the AccessKey ID, AccessKey secret, and STS token from environment variables. $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Use the default configuration of the SDK. $cfg = Oss\Config::loadDefault(); $cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider. $cfg->setRegion($region); // Specify the region in which the bucket is located. // Create an OSSClient instance. $client = new Oss\Client($cfg); // Use the OSSClient instance to perform subsequent operations.
Static credentials
The following example shows how to hardcode temporary access credentials in code:
Do not embed access credentials in application code deployed in a production environment. This method is intended only for testing.
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
# Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
$region = "cn-hangzhou";
# Specify the temporary AccessKey ID and AccessKey secret provided by STS, instead of the AccessKey ID and AccessKey secret of an Alibaba Cloud account.
# An AccessKey ID provided by STS starts with STS.
$stsAccessKeyId = 'STS.****************';
$stsAccessKeySecret = 'yourAccessKeySecret';
# Specify the STS token obtained from STS.
$stsSecurityToken = 'yourSecurityToken';
# Create a static credential provider and explicitly specify the AccessKey ID, AccessKey secret, and STS token provided by STS.
$credentialsProvider = new Oss\Credentials\StaticCredentialsProvider($stsAccessKeyId, $stsAccessKeySecret, $stsSecurityToken);
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Use the OSSClient instance to perform subsequent operations.
Configuration examples for other scenarios
Use the ARN of a RAM role
If you need to authorize your application to access OSS, for example, in a cross-account access scenario, you can use the Alibaba Cloud Resource Name (ARN) of a RAM role to initialize a credential provider. The underlying logic of this method is to use an STS token to configure access credentials. The Credentials tool obtains an STS token based on the ARN of the RAM role and refreshes the STS token by calling the AssumeRole operation before the session expires. You can specify a policy
to limit the permissions granted to the RAM role.
An Alibaba Cloud account has full permissions on its resources, and leaks of its AccessKey pair pose significant security risks. Therefore, we recommend that you use the AccessKey pair of a RAM user with the minimum required permissions to initialize a credential provider.
For information about how to create an AccessKey pair for a RAM user, see Create an AccessKey pair for a RAM user. You can record the AccessKey secret of a RAM user only when you create the RAM user. If you forget the AccesKey secret, you can create a new AccessKey pair for credential rotation.
You can create a RAM role by calling the CreateRole operation. The ARN of the RAM role is included in the response. For more information, see CreateRole.
Add the Alibaba Cloud credentials package credentials-php to your project.
composer require alibabacloud/credentials
Use an AccessKey pair and the ARN of a RAM role as access credentials.
<?php // Include the autoload file to load dependencies. require_once __DIR__ . '/../vendor/autoload.php'; use AlibabaCloud\Oss\V2 as Oss; use AlibabaCloud\Credentials\Credential; // Create a configuration object to define the credential type and related credential information. $config = new Credential\Config([ // Specify the credential type. In this example, the credential type is the ARN of a RAM role. 'type' => 'ram_role_arn', // Specify the AccessKey ID. 'accessKeyId' => 'AccessKeyId', // Specify the AccessKey secret. 'accessKeySecret' => 'AccessKeySecret', // Specify the ARN of a RAM role. The ARN is in the following format: acs:ram::USER_Id:role/ROLE_NAME 'roleArn' => 'RoleArn', // Specify a role session name to identify the session. 'roleSessionName' => 'yourRoleSessionName', // (Optional) Specify a policy to grant granular permissions to the STS token. 'policy' => 'Policy', ]); // Use the configuration object to initialize a Credential instance. $credential = new Credential($config); // Load the default configuration of the SDK. $cfg = Oss\Config::loadDefault(); // Set the credential provider and use a callback function to dynamically generate credentials. $cfg->setCredentialsProvider(new Oss\Credentials\CredentialsProviderFunc(function () use ($credential) { // Obtain the temporary credentials. $cred = $credential->getCredential(); // Return a Credentials object that contains the AccessKeyId, AccessKeySecret, and SecurityToken. return new Oss\Credentials\Credentials( accessKeyId: $cred->getAccessKeyId(), // The temporary AccessKey ID. accessKeySecret: $cred->getAccessKeySecret(), // The temporary AccessKey secret. securityToken: $cred->getSecurityToken() // The STS token. ); })); // Specify the region for the OSSClient instance. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. $region = 'cn-hangzhou'; $cfg->setRegion($region); // Create an OSSClient instance. $client = new Oss\Client($cfg); // Use the OSSClient instance to perform subsequent operations.
Use the RAM role of an ECS instance
If your application runs on an Elastic Compute Service (ECS) instance, an elastic container instance, or a Container Service for Kubernetes worker node, we recommend that you use the RAM role of the ECS instance to initialize a credential provider. The underlying logic of this method is to use an STS token to configure access credentials. You can attach a RAM role to an ECS instance, an elastic container instance, or a Container Service for Kubernetes worker node to automatically refresh the STS token on the instance. This method does not require an AccessKey pair or STS token, eliminating the risks associated with manually managing these credentials. You can create a RAM role by calling the CreateRole operation. The ARN is included in the response. For more information, see CreateRole.
Add the Alibaba Cloud credentials package credentials-php to your project.
composer require alibabacloud/credentials
Use the RAM role of an ECS instance to configure access credentials.
<?php // Include the autoload file to load dependencies. require_once 'vendor/autoload.php'; use AlibabaCloud\Oss\V2 as Oss; use AlibabaCloud\Credentials\Credential; // Create a configuration object to define the credential type and related credential information. $config = new Credential\Config([ // Specify the credential type. Since this example uses the RAM role of an ECS instance, the value is set to ecs_ram_role. 'type' => 'ecs_ram_role', // Specify the RAM role attached to the ECS instance. 'roleName' => "<role_name>", // Your role name. ]); // Use the configuration object to initialize a Credential instance. $credential = new Credential($config); // Load the default configuration. $cfg = Oss\Config::loadDefault(); // Set the credential provider and use a callback function to dynamically generate credentials. $cfg->setCredentialsProvider(new Oss\Credentials\CredentialsProviderFunc(function () use ($credential) { // Obtain the temporary credentials. $cred = $credential->getCredential(); // Return a Credentials object that contains the AccessKeyId, AccessKeySecret, and SecurityToken. return new Oss\Credentials\Credentials( accessKeyId: $cred->getAccessKeyId(), // The temporary AccessKey ID. accessKeySecret: $cred->getAccessKeySecret(), // The temporary AccessKey secret. securityToken: $cred->getSecurityToken() // The STS token. ); })); // Specify the region for the OSSClient instance. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. $region = 'cn-hangzhou'; $cfg->setRegion($region); // Create an OSSClient instance. $client = new Oss\Client($cfg); // Use the OSSClient instance to perform subsequent operations.
Use the RAM role of an OIDC IdP
After a RAM role is configured on a Container Service for Kubernetes worker node, applications within pods on the node can retrieve STS tokens for the attached role by using the metadata server in the same manner the applications deployed on an ECS instance retrieve STS tokens. However, if an untrusted application is deployed on the worker node, such as an application that is submitted by your customer and whose code is unavailable to you, you may not want the application to use the metadata server to obtain an STS token of the RAM role attached to the worker node. To ensure the security of cloud resources, allow untrusted applications to securely obtain required STS tokens, and minimize application-level permissions, you can use the RAM Roles for Service Account (RRSA) feature. The underlying logic of this method is to use an STS token to configure access credentials. Container Service for Kubernetes creates and mounts corresponding OIDC token files for different application pods, and passes relevant configuration information to environment variables. The Credentials tool obtains the configuration information from environment variables and calls the AssumeRoleWithOIDC operation of STS to obtain the STS token of attached roles. This method does not require an AccessKey pair or STS token, eliminating the risks associated with manually managing these credentials. For more information, see Use RRSA to authorize different pods to access different cloud services.
Add the Alibaba Cloud credentials package credentials-php to your project.
composer require alibabacloud/credentials
Use the role ARN of an OIDC IdP to configure access credentials.
<?php // Include the autoload file to load dependencies. require_once 'vendor/autoload.php'; use AlibabaCloud\Oss\V2 as Oss; use AlibabaCloud\Credentials\Credential; // Create a configuration object to define the credential type and related credential information. $config = new Credential\Config([ // Specify the credential type. In this example, the credential type is the role ARN of an OIDC IdP. 'type' => 'oidc_role_arn', // Specify the ARN of the OIDC IdP. You can set this value by using an environment variable, such as ALIBABA_CLOUD_OIDC_PROVIDER_ARN. 'oidcProviderArn' => '<oidc_provider_arn>', // Replace the value with actual ARN of the OIDC IdP. // Specify the path of the OIDC token file. You can set this value by using an environment variable, such as ALIBABA_CLOUD_OIDC_TOKEN_FILE. 'oidcTokenFilePath' => '<oidc_token_file_path>', // Replace the value with the actual path of the OIDC token file. // Specify the ARN of the RAM role. You can set this value by using an environment variable, such as ALIBABA_CLOUD_ROLE_ARN. 'roleArn' => '<role_arn>', // Replace the value with the actual ARN of the RAM role. // Specify the role session name. You can set this value by using an environment variable, such as ALIBABA_CLOUD_ROLE_SESSION_NAME. 'roleSessionName' => '<role_session_name>', // Replace the value with the actual session name. // (Optional) Specify a policy to grant granular permissions to the RAM role. // Example policy: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"} 'policy' => '', // If necessary, replace the value with the actual JSON policy string. // (Optional) Specify an expiration period (in seconds) for the session. The default value is 3600. 'roleSessionExpiration' => 3600, // If necessary, modify this value. ]); // Use the configuration object to initialize a Credential instance. $credential = new Credential($config); // Load the default configuration. $cfg = Oss\Config::loadDefault(); // Set the credential provider and use a callback function to dynamically generate credentials. $cfg->setCredentialsProvider(new Oss\Credentials\CredentialsProviderFunc(function () use ($credential) { // Obtain the temporary credentials. $cred = $credential->getCredential(); // Return a Credentials object that contains the AccessKeyId, AccessKeySecret, and SecurityToken. return new Oss\Credentials\Credentials( accessKeyId: $cred->getAccessKeyId(), // The temporary AccessKey ID. accessKeySecret: $cred->getAccessKeySecret(), // The temporary AccessKey secret. securityToken: $cred->getSecurityToken() // The STS token. ); })); // Specify the region for the OSSClient instance. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. $region = 'cn-hangzhou'; $cfg->setRegion($region); // Create an OSSClient instance. $client = new Oss\Client($cfg); // Use the OSSClient instance to perform subsequent operations.
Use custom access credentials
If the preceding credential configuration methods do not meet your business requirements, you can define a custom method for obtaining access credentials. The following methods are supported:
Oss\Credentials\CredentialsProviderFunc
Oss\Credentials\CredentialsProviderFunc is an encapsulation of Oss\Credentials\CredentialsProvider for better ease of use.
<?php // Include the autoload file to load dependencies. require_once 'vendor/autoload.php'; // Include required namespaces. use AlibabaCloud\Oss\V2 as Oss; use AlibabaCloud\Oss\V2\Credentials\Credentials; // Create a credential provider to dynamically generate credentials by using an anonymous function. $provider = new Oss\Credentials\CredentialsProviderFunc( function () { // Return the long-term access credentials, which consist of an AccessKey ID and an AccessKey secret. return new Credentials( accessKeyId: 'id', // Replace the value with the actual AccessKey ID of your RAM user. accessKeySecret: 'secret' // Replace the value with the actual AccessKey secret of your RAM user. ); // If you want to return temporary access credentials, uncomment the following lines and replace the values with your actual information. /* return new Credentials( accessKeyId: 'id', // Replace the value with the temporary AccessKey ID. accessKeySecret: 'secret', // Replace the value with the temporary AccessKey secret. securityToken: 'token' // Replace the value with the STS token. ); */ } ); // Load the default configuration. $cfg = Oss\Config::loadDefault(); // Set the credential provider. $cfg->setCredentialsProvider($provider); // Specify the region for the OSSClient instance. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. $region = 'cn-hangzhou'; $cfg->setRegion($region); // Create an OSSClient instance. $client = new Oss\Client($cfg); // Use the OSSClient instance to perform subsequent operations.
Oss\Credentials\CredentialsProvider
<?php // Include the autoload file to load dependencies. require_once 'vendor/autoload.php'; // Include required namespaces. use AlibabaCloud\Oss\V2 as Oss; use AlibabaCloud\Oss\V2\Credentials\Credentials; // Create a custom credential provider implementation of the CredentialsProvider class. class CustomerCredentialsProvider implements Oss\Credentials\CredentialsProvider { /** * The method that returns long-term or temporary access credentials * * @return Credentials A Crendentials object that contains access credentials. */ public function getCredentials(): Credentials { // Return the long-term access credentials, which consist of an AccessKey ID and an AccessKey secret. return new Credentials( accessKeyId: 'id', // Replace the value with the actual AccessKey ID of your RAM user. accessKeySecret: 'secret' // Replace the value with the actual AccessKey secret of your RAM user. ); // If you want to return temporary access credentials, uncomment the following lines and replace the values with your actual information. /* return new Credentials( accessKeyId: 'id', // Replace the value with the temporary AccessKey ID. accessKeySecret: 'secret', // Replace the value with the temporary AccessKey secret. securityToken: 'token' // Replace the value with the STS token. ); */ } } // Create an instance of the custom credential provider class. $provider = new CustomerCredentialsProvider(); // Load the default configuration. $cfg = Oss\Config::loadDefault(); // Set the credential provider. $cfg->setCredentialsProvider($provider); // Specify the region for the OSSClient instance. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. $region = 'cn-hangzhou'; $cfg->setRegion($region); // Create an OSSClient instance. $client = new Oss\Client($cfg); // Use the OSSClient instance to perform subsequent operations.