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. This topic describes how to configure temporary access credentials and long-term access credentials.
Prerequisites
OSS SDK for PHP is installed before you configure access credentials. For more information, see Installation.
Credential provider initialization
Credential providers
OSS supports multiple methods to initialize a credential provider. You can select a suitable method based on the authentication and authorization requirements of your actual scenario.
Initialization method | Scenario | AccessKey pair or security token required | Underlying credential | Credential validity period | Credential rotation or refresh method |
Applications are deployed and run in a secure and stable environment that is not vulnerable to external attacks and need to access cloud services for a long period of time without frequent credential rotation. | Yes | AK | Long-term | Manual rotation | |
Applications are deployed and run in an untrusted environment, in which case you want to manage the credential validity and the resources that can be accessed. | Yes | STS Token | Temporary | Manual refresh | |
Applications need to be authorized to access cloud services. For example, you can use this method to allow cross-account access to OSS. | Yes | STS Token | Temporary | Automatic refresh | |
Applications are deployed and run on Elastic Compute Service (ECS) instances, elastic container instances, and Container Service for Kubernetes (ACK) worker nodes. | No | STS Token | Temporary | Automatic refresh | |
Method 5: Use the Credentials parameter in the context of Function Compute | Applications are deployed and run in a function of Function Compute. | No | STS Token | Temporary | No need to refresh |
Untrusted applications are deployed and run on ACK worker nodes. | No | STS Token | Temporary | Automatic refresh | |
Applications require access credentials from external systems. | No | STS Token | Temporary | Automatic refresh | |
If none of the preceding methods meet your requirements, you can use a custom method to obtain access credentials. | Custom | Custom | Custom | Custom |
Method 1: Use an AccessKey pair
If your application is deployed in a secure and stable environment that is not vulnerable to external attacks and requires long-term access to OSS, you can use an AccessKey pair of your Alibaba Cloud account or a RAM user to initialize a credential provider. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. Take note that this method requires you to manually maintain an AccessKey pair. This poses security risks and increases maintenance complexity. For more information about how to obtain an AccessKey pair, see CreateAccessKey.
Environment variables
An Alibaba Cloud account has full permissions on resources within the account. Leaks of the Alibaba Cloud account AccessKey pair pose critical security threats. Therefore, we recommend that you use the AccessKey pair of a RAM user that is granted the minimum necessary permissions to initialize a credential provider.
Use the AccessKey pair to specify 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 by using environment variables.
<?php require_once __DIR__ . '/vendor/autoload.php'; use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\Core\OssException; try { // Obtain access credentials from environment variables and save the credentials in the provider. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. $provider = new EnvironmentVariableCredentialsProvider(); // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the 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 define access credentials by using variables in your code. During the code execution, these variables are populated with actual credential values obtained from environment variables, configuration files, or other external locations.
The following procedure describes how to use a configuration file to provide credentials:
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 by 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'); // Obtain 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 a security token
If your application needs to access OSS temporarily, you can use temporary access credentials, which consist of an AccessKey pair and a security token, obtained from Security Token Service (STS). Take note that this method requires you to manually maintain a security token. This poses security risks and increases maintenance complexity. If you want to access OSS multiple times, you must manually refresh the security token. For more information about how to obtain a security token, see AssumeRole.
Use the temporary access credentials to specify 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 by using environment variables.
<?php require_once __DIR__ . '/vendor/autoload.php'; use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\Core\OssException; try { // Obtain access credentials from environment variables and save the credentials in the provider. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables are configured. $provider = new EnvironmentVariableCredentialsProvider(); // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the 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 you need to authorize your application to access OSS, for example, when your application requires access to OSS resources of another Alibaba Cloud account, you can use RAMRoleARN to initialize a credential provider. The underlying logic of this method is to use a security token obtained from STS to configure access credentials. With the specified the Alibaba Cloud Resource Name (ARN) of a RAM role, the Credentials tool obtains a security token from STS and automatically refreshes the security token before the session expires. You can assign a value to the policy
parameter to limit the permissions of the RAM role. Take note that this method requires you to manually provide an AccessKey pair. This poses security risks and increases maintenance complexity. For more information about how to obtain an AccessKey pair, see CreateAccessKey. For more information about how to obtain a RAM role ARN, see CreateRole.
Add the credential client dependencies.
composer require alibabacloud/credentials
Configure 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([ // Set the credential type to ram_role_arn. 'type' => 'ram_role_arn', // Obtain the AccessKey pair of the RAM user from the environment variables. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 'accessKeyId' => getenv('OSS_ACCESS_KEY_ID'), 'accessKeySecret' => getenv('OSS_ACCESS_KEY_SECRET'), // Obtain the ARN of the RAM role from the environment variable, which is the ID of the RAM role to be assumed. Format: acs:ram::$accountID:role/$roleName. 'roleArn' => getenv('OSS_STS_ROLE_ARN'), // Specify a custom session name for the role to distinguish different tokens. 'roleSessionName' => 'yourRoleSessionName', // Specify a custom policy. 'policy' => '', ]); $credential = new Credential($config); $providerWrapper = new AlibabaCloudCredentialsWrapper($credential); $provider = $providerWrapper->getCredentials(); $config = array( 'provider' => $provider, // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your 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
Take note that this method requires alibabacloud/credentials 1.2.0 or later.
If your application runs on an ECS instance, an elastic container instance, or an ACK worker node, we recommend that you use ECSRAMRole to initialize a credential provider. The underlying logic of this method is to use a security token obtained from STS to configure access credentials. ECSRAMRole allows you to attach a RAM role to an ECS instance, an elastic container instance, or an ACK worker node to automatically refresh the security token on the instance. This method eliminates the risks that may arise when you manually maintain an AccessKey pair or a security token. For more information about how to obtain ECSRAMRole, see CreateRole.
Add the credential client dependencies.
composer require alibabacloud/credentials
Configure 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([ // Set the credential type 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, // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your 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 the Credentials parameter in the context of Function Compute
If the function of your application is deployed and run in Function Compute, you can initialize the credential provider by using the Credentials parameter in the context of Function Compute context. The underlying logic of this method is to use a security token obtained from STS to configure access credentials. Function Compute obtains a security token by assuming a service role based on the role configured for the function. Then, the security token is passed to your application by using the Credentials variable in the context. The security token is valid for 36 hours. You cannot change its validity period. The maximum execution time of a function is 24 hours. Therefore, you do not need to refresh the security token because it does not expire when the function is executed. This method eliminates the risks that may arise when you manually maintain an AccessKey pair or a security token. For more information about how to authorize Function Compute to access OSS, see Grant Function Compute permissions to access other Alibaba Cloud services.
Initialize the credential provider by using the Credentials parameter in the Function Compute context.
<?php use OSS\OssClient; use OSS\Core\OssException; function handler($event, $context) { /* The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. We recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. In this example, the AccessKey ID and AccessKey secret are obtained 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
Take note that this method requires alibabacloud/credentials 1.2.0 or later.
After the RAM role is configured on the ACK worker node, the application in a pod on the node can obtain the security token of the attached role by using the metadata server in the same manner as an application deployed on an ECS instance does. 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 a security token of the RAM role attached to the worker node. To ensure the security of cloud resources, allow untrusted applications to securely obtain the required security token, 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 a security token obtained from STS to configure access credentials. ACK creates and mounts corresponding OpenID Connect (OIDC) token files for different application pods, and passes relevant configuration information to environment variables. The Credentials tool obtains the configuration information of environment variables and calls the AssumeRoleWithOIDC operation of STS to obtain the security token of attached roles. This method eliminates the risks that may arise when you manually maintain an AccessKey pair or a security token. For more information, see Use RRSA to authorize different pods to access different cloud services.
Add the credential client dependencies.
composer require alibabacloud/credentials
Example:
<?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 { // Use the RAM role of an OIDC IdP to initialize a Credentials client. $config = new Credential\Config([ // Specify the credential type. 'type' => 'oidc_role_arn', // Specify the ARN of the OIDC IdP by specifying the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable. 'oidcProviderArn' => '<OidcProviderArn>', // Specify the path of the OIDC token file by specifying the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable. 'oidcTokenFilePath' => '<OidcTokenFilePath>', // Specify the ARN of the RAM role by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole. 'roleArn' => '<RoleArn>', // Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. 'roleSessionName' => '<RoleSessionName>', // Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}. 'policy' => '<Policy>', # Specify the validity period of the session. 'durationSeconds' => 3600, ]); $credential = new Credential($config); $providerWrapper = new AlibabaCloudCredentialsWrapper($credential); $provider = $providerWrapper->getCredentials(); $config = array( 'provider' => $provider, // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your 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
Take note that this method requires alibabacloud/credentials 1.2.0 or later.
If your application needs to obtain an Alibaba Cloud credential from an external system to implement flexible credential management and keyless access, you can use the CredentialsURI to initialize a credential provider. The underlying logic of this method is to use a security token obtained from STS to configure access credentials. The Credentials tool obtains the security token by using the URI that you specify to initialize an OSSClient instance on the client. This method eliminates the risks that may arise when you manually maintain an AccessKey pair or a security token. Take note that the backend service that provides the CredentialsURI response must automatically refresh the security token to ensure that your application can always obtain a valid credential.
Add the credential client dependencies.
composer require alibabacloud/credentials
Example:
<?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([ // Specify the credential type. 'type' => 'credentials_uri', // Obtain the URI of the credential in the http://local_or_remote_uri/ format by specifying the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. 'credentialsURI' => '<CredentialsUri>', ]); $credential = new Credential($config); $providerWrapper = new AlibabaCloudCredentialsWrapper($credential); $provider = $providerWrapper->getCredentials(); $config = array( 'provider' => $provider, // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your 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 a custom method to obtain access credentials
If none of the preceding methods meet your requirements, you can use a custom method to obtain access credentials by calling the Credential Providers operation.
<?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, use the credential provider to create an OSSClient instance. For more information, see Initialization.