To send requests to OSS using the PHP SDK, you must configure access credentials. Alibaba Cloud services use these credentials to verify your identity and access permissions. You can choose from different types of access credentials based on your authentication and authorization requirements. This topic describes how to configure temporary and long-term access credentials.
Prerequisites
Before you configure access credentials, you must install the OSS PHP SDK. For more information, see Installation (PHP SDK V1).
Initialize a credential provider
Choose a credential provider
OSS supports multiple methods for initializing a credential provider. You can choose a method based on the authentication and authorization requirements of your scenario.
Initialization method | Scenario | Requires an existing AccessKey or STS token | Underlying credential | Credential validity period | Credential rotation or refresh method |
Applications that run in a secure environment and need long-term access to Alibaba Cloud services without frequent credential rotation. | Yes | AccessKey | Long-term | Manual rotation | |
Applications that run in an untrusted environment where you need to control the validity period and access permissions. | Yes | STS token | Temporary | Manual refresh | |
Applications that need authorized access to Alibaba Cloud services, such as for cross-account access. | Yes | STS token | Temporary | Auto-refresh | |
Applications that run on Alibaba Cloud ECS instances, ECI instances, or Container Service for Kubernetes worker nodes. | No | STS token | Temporary | Auto-refresh | |
Functions of applications that run in Alibaba Cloud Function Compute. | No | STS token | Temporary | No refresh needed | |
Untrusted applications that run on Container Service for Kubernetes worker nodes. | No | STS token | Temporary | Auto-refresh | |
Applications that need to get access credentials from an external system. | No | STS token | Temporary | Auto-refresh | |
If the preceding methods do not meet your requirements, you can define a custom method to get credentials. | Custom | Custom | Custom | Custom |
Method 1: Use an AccessKey pair
If your application runs in a secure environment and requires long-term access to OSS without frequent credential rotation, you can initialize the credential provider using an AccessKey pair from an Alibaba Cloud account or a Resource Access Management (RAM) user. An AccessKey pair consists of an AccessKey ID and an AccessKey secret. This method requires you to manually maintain the AccessKey pair, which can increase security risks and maintenance complexity. For more information, see CreateAccessKey - Create an AccessKey pair for an Alibaba Cloud account or a RAM user.
Environment variables
An Alibaba Cloud account has full permissions for its resources. If the AccessKey pair of an Alibaba Cloud account is leaked, it poses a critical security threat. We recommend that you use the AccessKey pair of a RAM user with the minimum required permissions.
Use an AccessKey pair to set environment variables.
Mac OS X/Linux/Unix
export OSS_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> export OSS_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>Windows
set OSS_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> set OSS_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>Pass credential information using environment variables.
<?php require_once __DIR__ . '/vendor/autoload.php'; use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\Core\OssException; try { // Get access credentials from environment variables and save them in the provider. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. $provider = new EnvironmentVariableCredentialsProvider(); // Set Endpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com. $endpoint = "http://oss-cn-hangzhou.aliyuncs.com"; $bucket = "bucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); var_dump($ossClient); } catch (OssException $e) { printf($e->getMessage() . "\n"); return; }
Static credentials
You can use variables in your code to reference credentials. At runtime, these variables are assigned the actual credential values from environment variables, configuration files, or other external data sources.
The following steps show an example that uses a configuration file.
Create a configuration file named
config.ini.[credentials] alibaba_cloud_access_key_id = <ALIBABA_CLOUD_ACCESS_KEY_ID> alibaba_cloud_access_key_secret = <ALIBABA_CLOUD_ACCESS_KEY_SECRET>Pass credential information using the configuration file.
<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } use OSS\Credentials\StaticCredentialsProvider; use OSS\OssClient; use OSS\Core\OssException; try { $config = parse_ini_file('config.ini'); // Get the AccessKey ID and AccessKey secret. $accessKeyId = $config['alibaba_cloud_access_key_id']; $accessKeySecret = $config['alibaba_cloud_access_key_secret']; $provider = new StaticCredentialsProvider($accessKeyId,$accessKeySecret); $endpoint = "http://oss-cn-hangzhou.aliyuncs.com"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); printf($ossClient); } catch (OssException $e) { printf($e->getMessage() . "\n"); return; }
Method 2: Use an STS token
If your application needs temporary access to OSS, you can initialize the credential provider using temporary identity credentials from the Security Token Service (STS). These credentials include an AccessKey ID, an AccessKey secret, and a security token. This method requires you to manually maintain the STS token, which can increase security risks and maintenance complexity. To access OSS multiple times, you must manually refresh the STS token. For more information, see AssumeRole - Get temporary identity credentials for a RAM role.
Use temporary identity credentials to set environment variables.
Mac OS X/Linux/Unix
export OSS_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> export OSS_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET> export OSS_SESSION_TOKEN=<ALIBABA_CLOUD_SECURITY_TOKEN>Windows
set OSS_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> set OSS_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET> set OSS_SESSION_TOKEN=<ALIBABA_CLOUD_SECURITY_TOKEN>Pass credential information using environment variables.
<?php require_once __DIR__ . '/vendor/autoload.php'; use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\Core\OssException; try { // Get access credentials from environment variables and save them in the provider. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables are set. $provider = new EnvironmentVariableCredentialsProvider(); // Set Endpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com. $endpoint = "http://oss-cn-hangzhou.aliyuncs.com"; $bucket = "bucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); var_dump($ossClient); } catch (OssException $e) { printf($e->getMessage() . "\n"); return; }
Method 3: Use RAMRoleARN
This method requires alibabacloud/credentials 1.2.0 or later.
If your application needs authorization to access OSS, such as for cross-account access, you can use RAMRoleARN to initialize the credential provider. This method uses an STS token as the underlying credential. By specifying the Alibaba Cloud Resource Name (ARN) of a RAM role, the Credentials tool retrieves an STS token from STS and automatically refreshes it before it expires. You can also assign a value to the policy parameter to restrict the RAM role to a smaller set of permissions. This method requires you to provide an AccessKey pair, which can increase security risks and maintenance complexity. For more information about how to obtain an AccessKey pair, see CreateAccessKey - Create an AccessKey pair for a RAM user. For more information about how to obtain a RAMRoleARN, see CreateRole - Create a RAM role.
Add the credential client dependency.
composer require alibabacloud/credentialsConfigure access credentials.
<?php require_once __DIR__ . '/vendor/autoload.php'; use AlibabaCloud\Credentials\Credential; use OSS\Core\OssException; use OSS\OssClient; use OSS\Credentials\CredentialsProvider; use OSS\Credentials\StaticCredentialsProvider; class AlibabaCloudCredentialsWrapper implements CredentialsProvider { /** * @var Credential */ private $wrapper; public function __construct($wrapper) { $this->wrapper = $wrapper; } public function getCredentials() { $cred = $this->wrapper->getCredential(); $ak = $cred->getAccessKeyId(); $sk = $cred->getAccessKeySecret(); $token = $cred->getSecurityToken(); return new StaticCredentialsProvider($ak, $sk, $token); } } try { $config = new Credential\Config([ // The credential type. Set the value to ram_role_arn. 'type' => 'ram_role_arn', // Get the AccessKey pair (AccessKey ID and AccessKey secret) of the RAM user from environment variables. 'accessKeyId' => getenv('OSS_ACCESS_KEY_ID'), 'accessKeySecret' => getenv('OSS_ACCESS_KEY_SECRET'), // Get the ARN of the RAM role from the environment variable. This is the ID of the role to assume, in the format acs:ram::$accountID:role/$roleName. 'roleArn' => getenv('OSS_STS_ROLE_ARN'), // A custom role session name to distinguish different tokens. 'roleSessionName' => 'yourRoleSessionName', // A custom access policy. 'policy' => '', ]); $credential = new Credential($config); $providerWrapper = new AlibabaCloudCredentialsWrapper($credential); $provider = $providerWrapper->getCredentials(); $config = array( 'provider' => $provider, // For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint. 'endpoint' => 'https://oss-cn-hangzhou.aliyuncs.com' "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); var_dump($ossClient); } catch (OssException $e) { print $e->getMessage(); }
Method 4: Use ECSRAMRole
This method requires alibabacloud/credentials 1.2.0 or later.
If your application runs on an ECS instance, ECI instance, or Container Service for Kubernetes worker node, you can use ECSRAMRole to initialize the credential provider. This method uses an STS token as the underlying credential. ECSRAMRole lets you attach a RAM role to an ECS instance, ECI instance, or Container Service for Kubernetes worker node to automatically refresh the STS token on the instance. This method eliminates the risks associated with manually maintaining an AccessKey pair or an STS token. For more information about how to obtain an ECSRAMRole, see CreateRole - Create a RAM role.
Add the credential client dependency.
composer require alibabacloud/credentialsConfigure ECSRAMRole as the access credential.
<?php require_once __DIR__ . '/vendor/autoload.php'; use AlibabaCloud\Credentials\Credential; use OSS\Core\OssException; use OSS\OssClient; use OSS\Credentials\CredentialsProvider; use OSS\Credentials\StaticCredentialsProvider; class AlibabaCloudCredentialsWrapper implements CredentialsProvider { /** * @var Credential */ private $wrapper; public function __construct($wrapper) { $this->wrapper = $wrapper; } public function getCredentials() { $cred = $this->wrapper->getCredential(); $ak = $cred->getAccessKeyId(); $sk = $cred->getAccessKeySecret(); $token = $cred->getSecurityToken(); return new StaticCredentialsProvider($ak, $sk, $token); } } try { $config = new Credential\Config([ // The credential type. Set the value to ecs_ram_role. 'type' => 'ecs_ram_role', 'roleName' => "<role_name>", ]); $credential = new Credential($config); $providerWrapper = new AlibabaCloudCredentialsWrapper($credential); $provider = $providerWrapper->getCredentials(); $config = array( 'provider' => $provider, // For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint. 'endpoint' => 'https://oss-cn-hangzhou.aliyuncs.com' "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); var_dump($ossClient); } catch (OssException $e) { print $e->getMessage(); }
Method 5: Use credentials from the Function Compute context
If your application's function runs in Function Compute, you can use the credentials in the function context to initialize the credential provider. This method uses an STS token as the underlying credential. Function Compute obtains an STS token by assuming a service role based on the function's configuration. The STS token is then passed to your application through the Credentials parameter in the context. The STS token is valid for 36 hours, and this period cannot be changed. The maximum running time of a function is 24 hours. Therefore, the STS token does not expire during function execution, and you do not need to refresh it. This method eliminates the risks associated with manually maintaining an AccessKey pair or an STS token. For more information about how to grant Function Compute permissions to access OSS, see Use a function role to grant Function Compute permissions to access other Alibaba Cloud services.
Initialize the credential provider using the credentials from the Function Compute context.
<?php use OSS\OssClient; use OSS\Core\OssException; function handler($event, $context) { /* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user for API access or routine O&M. Do not hard-code your AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all your resources may be compromised. This example shows how to get the AccessKey ID and AccessKey secret from the context. */ $creds = $context["credentials"]; $accessKeyId = $creds["accessKeyId"]; $accessKeySecret = $creds["accessKeySecret"]; $securityToken = $creds["securityToken"]; $endpoint = "https://oss-cn-hangzhou-internal.aliyuncs.com"; try{ $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken); print_r($ossClient); } catch(OssException $e) { printf(__FUNCTION__ . ": FAILED\n"); printf($e->getMessage() . "\n"); return $e->getMessage(); } return 'hello world'; }
Method 6: Use OIDCRoleARN
This method requires alibabacloud/credentials 1.2.0 or later.
After you configure a RAM role for a Container Service for Kubernetes worker node, applications in pods on that node can obtain the STS token of the associated role from the metadata server. This is similar to how applications on an ECS instance work. However, if untrusted applications are deployed on the cluster, you may not want them to obtain the STS token of the instance RAM role from the metadata server. An example is an application submitted by your customer whose code is not open to you. To protect your cloud resources and allow these untrusted applications to securely obtain the required STS tokens with minimum permissions, you can use the RAM Roles for Service Account (RRSA) feature. This method uses an STS token as the underlying credential. An Alibaba Cloud container cluster creates and mounts the corresponding service account OpenID Connect (OIDC) token file for each application pod. It also injects the configuration information into environment variables. The Credentials tool retrieves the configuration from the environment variables and calls the AssumeRoleWithOIDC operation of STS to exchange the OIDC token for an STS token of the bound role. This method eliminates the risks associated with manually maintaining an AccessKey pair or an STS token. For more information, see Pod permission isolation based on RRSA.
Add the credential client dependency.
composer require alibabacloud/credentialsThe following sample code shows how to configure the RAM role of an OIDC provider as the access credential.
<?php require_once __DIR__ . '/vendor/autoload.php'; use OSS\Credentials\CredentialsProvider; use AlibabaCloud\Credentials\Credential; use OSS\Credentials\StaticCredentialsProvider; use OSS\Core\OssException; use OSS\OssClient; class AlibabaCloudCredentialsWrapper implements CredentialsProvider { /** * @var Credential */ private $wrapper; public function __construct($wrapper) { $this->wrapper = $wrapper; } public function getCredentials() { $cred = $this->wrapper->getCredential(); $ak = $cred->getAccessKeyId(); $sk = $cred->getAccessKeySecret(); $token = $cred->getSecurityToken(); return new StaticCredentialsProvider($ak, $sk, $token); } } try { // Initialize the Credentials Client using OIDCRoleArn. $config = new Credential\Config([ // The credential type. 'type' => 'oidc_role_arn', // The ARN of the OIDC provider. You can set oidc_provider_arn using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable. 'oidcProviderArn' => '<OidcProviderArn>', // The path of the OIDC token file. You can set oidc_token_file_path using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable. 'oidcTokenFilePath' => '<OidcTokenFilePath>', // The ARN of the RAM role. Example: acs:ram::123456789012****:role/adminrole. You can set role_arn using the ALIBABA_CLOUD_ROLE_ARN environment variable. 'roleArn' => '<RoleArn>', // The role session name. You can set role_session_name using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. 'roleSessionName' => '<RoleSessionName>', // Optional. A smaller access policy. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"} 'policy' => '<Policy>', # Set the session expiration time. 'durationSeconds' => 3600, ]); $credential = new Credential($config); $providerWrapper = new AlibabaCloudCredentialsWrapper($credential); $provider = $providerWrapper->getCredentials(); $config = array( 'provider' => $provider, // For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint. 'endpoint' => 'https://oss-cn-hangzhou.aliyuncs.com' "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); var_dump($ossClient); } catch (OssException $e) { print $e->getMessage(); }
Method 7: Use CredentialsURI
This method requires alibabacloud/credentials 1.2.0 or later.
If your application needs to obtain Alibaba Cloud credentials from an external system for flexible credential management and keyless access, you can use CredentialsURI to initialize the credential provider. This method uses an STS token as the underlying credential. The Credentials tool obtains an STS token from the URI you provide to initialize the credential client. This method eliminates the risks associated with manually maintaining an AccessKey pair or an STS token. The backend service that provides the CredentialsURI response must implement the logic to automatically refresh the STS token. This ensures that your application always has a valid credential.
Add the credential client dependency.
composer require alibabacloud/credentialsThe following sample code shows how to configure CredentialsURI as the access credential.
<?php require_once __DIR__ . '/vendor/autoload.php'; use AlibabaCloud\Credentials\Credential; use OSS\Core\OssException; use OSS\Credentials\CredentialsProvider; use OSS\Credentials\StaticCredentialsProvider; use OSS\OssClient; class AlibabaCloudCredentialsWrapper implements CredentialsProvider { /** * @var Credential */ private $wrapper; public function __construct($wrapper) { $this->wrapper = $wrapper; } public function getCredentials() { $cred = $this->wrapper->getCredential(); $ak = $cred->getAccessKeyId(); $sk = $cred->getAccessKeySecret(); $token = $cred->getSecurityToken(); return new StaticCredentialsProvider($ak, $sk, $token); } } try { $config = new Credential\Config([ // The credential type. 'type' => 'credentials_uri', // The URI of the credential, in the format http://local_or_remote_uri/. You can set credentials_uri using the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. 'credentialsURI' => '<CredentialsUri>', ]); $credential = new Credential($config); $providerWrapper = new AlibabaCloudCredentialsWrapper($credential); $provider = $providerWrapper->getCredentials(); $config = array( 'provider' => $provider, // For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint. 'endpoint' => 'https://oss-cn-hangzhou.aliyuncs.com' "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); var_dump($ossClient); } catch (OssException $e) { print $e->getMessage(); }
Method 8: Use custom access credentials
If none of the preceding methods meet your requirements, you can define a custom credential provider by implementing the Credential Providers interface.
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\CredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;
class CustomerCredentialsProvider implements CredentialsProvider
{
public function getCredentials()
{
// Return long-term credentials.
return [
'AccessKeyId' => 'id',
'AccessKeySecret' => 'secret',
];
// Return temporary credentials.
//return [
// 'AccessKeyId' => 'id',
// 'AccessKeySecret' => 'secret',
// 'SecurityToken' => 'token',
//];
}
}
$provider = new CustomerCredentialsProvider();
try {
$provider = new CustomerCredentialsProvider();
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
printf($ossClient);
} catch (OssException $e) {
printf($e->getMessage() . "\n");
return;
}
What to do next
After you initialize the credential provider, you can use it to create an OSSClient instance. For more information, see Initialization (PHP SDK V1).