This topic describes how to use temporary access credentials provided by Security Token Service (STS) or a signed URL to temporarily access Object Storage Service (OSS) resources.
Usage notes
- A validity period must be specified for temporary access credentials and a signed URL. When you use temporary access credentials to generate a signed URL that is used to perform operations, such as object upload and download, the minimum validity period takes precedence. For example, you can set the validity period of your temporary access credentials to 1,200 seconds and the validity period of the signed URL generated by using the credentials to 3,600 seconds. In this case, the signed URL cannot be used to upload objects after the STS temporary access credentials expire, although the signed URL is within its validity period.
- In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS by using other Alibaba Cloud services in the same region as OSS, use an internal endpoint For more information about the regions and endpoints supported by OSS, see Regions and endpoints.
- In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or STS, see Create an OSSClient instance.
Use STS for temporary access authorization
You can use Alibaba Cloud STS to authorize temporary access to OSS. STS is a web service that provides temporary access tokens for users. You can use STS to grant temporary access credentials that have a custom validity period and custom permissions to a third-party application or a RAM user that is managed by you. For more information about STS, see What is STS?
STS provides the following benefits:
- You need to only generate an access token and send the access token to a third-party application. You do not need to expose your AccessKey pair to the third-party application. You can specify the access permissions and the validity period of the token.
- The token automatically expires after the validity period. Therefore, you do not need to manually revoke the access permissions of a token.
To access OSS by using temporary access credentials provided by STS, perform the following operations:
Step 1: Create a RAM user
- Log on to the RAM console.
- In the left-side navigation pane, choose .
- On the Users page, click Create User.
- Specify the Logon Name and Display Name parameters.
- In the Access Mode section, select OpenAPI Access and click OK.
- Click Copy to save the AccessKey pair of the RAM user.
Step 2: Grant the RAM user the AssumeRole permission
- On the Users page, click Add Permissions in the Actions column corresponding to the created RAM user.
- In the Add Permissions panel, select the AliyunSTSAssumeRoleAccess policy from the policy list for System Policy.
- Click OK.
Step 3: Create a role used to obtain temporary access credentials from STS.
- In the left-side navigation pane, choose .
- Click Create Role. In the Create Role panel, set Select Trusted Entity to Alibaba Cloud Account and click Next.
- Set RAM Role Name to RamOssTest and Select Trusted Alibaba Cloud Account to Current Alibaba Cloud Account.
- Click OK. After the role is created, click Close.
- On the Roles page, enter RamOssTest in the search box.
- Click Copy to save the Alibaba Cloud Resource Name (ARN) of the role.
Step 4: Grant the role the permissions to upload objects to and download objects from OSS.
- Grant the role the permissions to upload objects to and download objects from a bucket by using custom policies.
- In the left-side navigation pane, choose .
- On the Policies page, click Create Policy.
- On the Create Policy page, click JSON. Modify the script in the policy editor to grant the role the permissions to upload objects to and download objects from a bucket named examplebucket by calling PutObject and GetObject. The following sample code provides an example on how to grant the role the permissions. Warning The following example is for reference only. To avoid granting users excessive permissions on resources, you must configure fine-grained RAM policies based on your requirements. For more information about how to configure fine-grained RAM policies, see Common examples of RAM policies.
{ "Version": "1", "Statement": [ { "Effect": "Allow", "Action": [ "oss:PutObject", "oss:GetObject" ], "Resource": [ "acs:oss:*:*:examplebucket", "acs:oss:*:*:examplebucket/*" ] } ] }
- Click Next Step.
- In the Basic Information section, set Policy Name to RamTestPolicy and click OK.
- Attach the custom policy to the RamOssTest role.
- In the left-side navigation pane, choose .
- On the Roles page, find the RamOssTest role.
- Click Add Permissions in the Actions column corresponding to the RamOssTest role.
- In the Add Permissions panel, click the Custom Policy tab and select the RamTestPolicy policy.
- Click OK.
Step 5: Generate temporary access credentials by using STS
The temporary access credentials consist of an AccessKey pair and a security token. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. The minimum validity period of temporary access credentials is 900 seconds. The maximum validity period of temporary access credentials is the maximum session duration specified for the current role. For more information, see Specify the maximum session duration for a RAM role.
<?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 AlibabaCloud\SDK\Sts\V20150401\Sts;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Sts\V20150401\Models\AssumeRoleRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
try {
// Specify the AccessKey pair that is created for the RAM user in Step 1.
$config = new Config([
"accessKeyId" => "accessKeyId",
"accessKeySecret" => "accessKeySecret"
]);
//
$config->endpoint = "sts.cn-hangzhou.aliyuncs.com";
$client = new Sts($config);
$assumeRoleRequest = new AssumeRoleRequest([
// Specify the Alibaba Cloud Resource Name (ARN) of the role that is created in Step 3. Example: acs:ram::175708322470****:role/ramtest.
"roleArn" => "acs:ram::175708322470****:role/ramtest",
// Specify roleSessionName to distinguish different tokens. roleSessionName specifies a custom role session name, such as sessiontest.
"roleSessionName" => "sessiontest",
// Specify durationSeconds. durationSeconds specifies the validity period of the temporary access credentials. The minimum value is 900. The maximum value is the maximum session duration that the current role specifies. Unit: seconds. In this example, the validity period is set to 3,000 seconds.
"durationSeconds" => 3000,
// Specify the custom policies. This way, you can limit the permissions of the temporary access credentials. If you do not specify custom policies, the returned temporary access credentials have full permissions of the specified RAM role.
// The permissions obtained by the temporary access credentials are the intersection of the role permissions configured in Step 4 and the permissions specified by the RAM policy.
// "policy" => ""
]);
$runtime = new RuntimeOptions([]);
$result = $client->assumeRoleWithOptions($assumeRoleRequest, $runtime);
printf("AccessKeyId:" . $result->body->credentials->accessKeyId. PHP_EOL);
printf("AccessKeySecret:".$result->body->credentials->accessKeySecret.PHP_EOL);
printf("Expiration:".$result->body->credentials->expiration.PHP_EOL);
printf("SecurityToken:".$result->body->credentials->securityToken.PHP_EOL);
}catch (Exception $e){
printf($e->getMessage() . PHP_EOL);
}
Step 6: Use the temporary access credentials to upload objects to and download objects from OSS
- Use the temporary access credentials to upload objects to OSS
<?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\OssClient; use OSS\Core\OssException; // Specify the temporary AccessKey pair obtained from STS. $accessKeyId = "yourAccessKeyId"; $accessKeySecret = "yourAccessKeySecret"; // Specify the security token obtained from STS. $securityToken = "yourSecurityToken"; // 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 = "yourEndpoint"; // Specify the name of the bucket. $bucket= "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. $object = "exampleobject.txt"; // Specify the string that you want to upload. $content = "Hello OSS"; try { $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken); // Upload the object by using the temporary access credentials obtained from STS. $ossClient->putObject($bucket, $object, $content); } catch (OssException $e) { print $e->getMessage(); }
- Use the temporary access credentials to download objects from OSS
<?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\OssClient; use OSS\Core\OssException; // Specify the temporary AccessKey pair obtained from STS. $accessKeyId = "yourAccessKeyId"; $accessKeySecret = "yourAccessKeySecret"; // Specify the security token obtained from STS. $securityToken = "yourSecurityToken"; // 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 = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the name of the bucket. $bucket= "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. $object = "exampleobject.txt"; // Download the object to the local path D:\\localpath as a local file named examplefile.txt. If a file with the same name already exists, the downloaded object overwrites the file. Otherwise, the downloaded object is saved in the path. // If you do not specify the path of the local file, the downloaded object is saved to the path of the project to which the sample program belongs. $localfile = "D:\\localpath\\examplefile.txt"; $options = array( OssClient::OSS_FILE_DOWNLOAD => $localfile ); // Use try catch to catch exceptions. If an exception is caught, the download fails. If no exceptions are caught, the download succeeds. try{ $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken); $ossClient->getObject($bucket, $object, $options); } catch(OssException $e) { printf(__FUNCTION__ . ": FAILED\n"); printf($e->getMessage() . "\n"); return; } print(__FUNCTION__ . ": OK, please check localfile: 'upload-test-object-name.txt'" . "\n"); }
Use a signed URL for temporary access authorization
You can generate a signed URL and provide the URL to a visitor for temporary access. When you generate a signed URL, you can specify the validity period of the URL to limit the period of time during which the visitor can access OSS. For the complete sample code for access authorization, visit GitHub.
+
), you may fail to access OSS by using the URL. In this case, you must replace the plus sign (+
) in the URL with %2B
. Generate a signed URL that includes the versionId header
The following sample code provides an example on how to generate a signed URL that includes the versionId header.
<?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\OssClient;
use OSS\Core\OssException;
// 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. To create a RAM user, log on to the RAM console.
$accessKeyId = "yourAccessKeyId";
$accessKeySecret = "yourAccessKeySecret";
// 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 = "yourEndpoint";
// Specify the name of the bucket.
$bucket= "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path.
$object = "exampleobject.txt";
// Set the validity period of a signed URL to 3,600 seconds.
$timeout = 3600;
try{
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
$options = array(
// Specify the version ID of the object.
$ossClient::OSS_VERSION_ID=>"CAEQEhiBgIDmgPf8mxgiIDA1YjZlNDIxY2ZmMzQ1MmU5MTM1Y2M4Yzk4NjIx****"
);
// Generate a signed URL.
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
printf('Sign Url:'.$signedUrl. "\n");
} catch(OssException $e) {
printf($e->getMessage() . "\n");
}
Generate a signed URL and use the signed URL to upload an object
- Generate a signed URL
<?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\OssClient; use OSS\Core\OssException; use OSS\Http\RequestCore; use OSS\Http\ResponseCore; // Specify the temporary AccessKey pair obtained from STS. An AccessKey pair consists of an AccessKey ID and an AccessKey secret. $accessKeyId = "yourAccessKeyId"; $accessKeySecret = "yourAccessKeySecret"; // Specify the security token obtained from STS. $securityToken = "yourSecurityToken"; // 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 = "yourEndpoint"; // Specify the name of the bucket. $bucket= "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. $object = "exampleobject.txt"; // Set the validity period of a signed URL to 3,600 seconds. $timeout = 3600; try { $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken); // Generate a signed URL. $signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "PUT"); } catch (OssException $e) { printf(__FUNCTION__ . ": FAILED\n"); printf($e->getMessage() . "\n"); return; } print(__FUNCTION__ . ": signedUrl: " . $signedUrl . "\n");
- Upload an object by using the signed URL
You can refer to OSS SDK for Android mobile devices. For more information, see Upload an object by using the signed URL.
Generate a signed URL and use the signed URL to download an object
- Generate a signed URL
<?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\OssClient; use OSS\Core\OssException; use OSS\Http\RequestCore; use OSS\Http\ResponseCore; // Specify the temporary AccessKey pair obtained from STS. An AccessKey pair consists of an AccessKey ID and an AccessKey secret. $accessKeyId = "yourAccessKeyId"; $accessKeySecret = "yourAccessKeySecret"; // Specify the security token obtained from STS. $securityToken = "yourSecurityToken"; // 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 = "yourEndpoint"; // Specify the name of the bucket. $bucket= "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. $object = "exampleobject.txt"; // Set the validity period of a signed URL to 3,600 seconds. $timeout = 3600; // Generate a signed URL that is used to preview the object and use the custom domain name that is mapped to the bucket to access the object. $options= array( "response-content-disposition"=>"inline",); // Generate a signed URL that is used to download the object. /*$options = array( "response-content-disposition"=>"attachment", );*/ try { $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken); $signedUrl = $ossClient->signUrl($bucket, $object, $timeout,'GET',$options); } catch (OssException $e) { printf(__FUNCTION__ . ": FAILED\n"); printf($e->getMessage() . "\n"); return; } print(__FUNCTION__ . ": signedUrl: " . $signedUrl . "\n");
- Download an object by using the signed URL
You can refer to OSS SDK for Android mobile devices. For more information, see Download an object by using the signed URL.