All Products
Search
Document Center

Object Storage Service:Authorize access by using OSS SDK for PHP

Last Updated:Nov 11, 2024

This topic describes how to use temporary access credentials provided by Security Token Service (STS) or a signed URL to authorize temporary access to Object Storage Service (OSS) resources.

Usage notes

  • A validity period must be specified for temporary access credentials obtained from STS 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 temporary access credentials expire, even if 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 from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions, endpoints and open ports.

  • 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 Security Token Service (STS), see Create an OSSClient instance.

Use STS to authorize temporary access

You can use 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 a temporary access token and send the access token to a third-party application. You do not need to provide your AccessKey pair to the third-party application. You can specify the access permissions and validity period of this token.

  • The token automatically expires after the validity period ends. 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.

  1. Log on to the RAM console.

  2. In the left-side navigation pane, choose Identities > Users.

  3. On the Users page, click Create User.

  4. Configure the Logon Name and Display Name parameters.

  5. In the Access Mode section, select OpenAPI Access. Then, click OK.

  6. Complete security verification as prompted.

  7. Copy the AccessKey pair (AccessKey ID and AccessKey secret).

    Important

    You can obtain the AccessKey secret of a RAM user only when you create the RAM user. You must keep the AccessKey secret safely to prevent credential leaks.

Step 2: Grant the RAM user the AssumeRole permission.

  1. On the Users page, find the RAM user that you created and click Add Permissions in the Actions column.

  2. In the Policy section of the Grant Permission panel, select the AliyunSTSAssumeRoleAccess policy.

    Note

    The AliyunSTSAssumeRoleAccess policy allows a RAM user to call the AssumeRole operation. The permissions of the policy are independent of the permissions required for the RAM user to obtain temporary access credentials from STS and initiate requests to OSS.

    image.png

  3. Click Grant permissions.

Step 3: Create a role used to obtain temporary access credentials from STS.

  1. In the left-side navigation pane, choose Identities > Roles.

  2. Click Create Role. In the Select Role Type step of the Create Role wizard, set Select Trusted Entity to Alibaba Cloud Account and click Next.

  3. In the Configure Role step of the Create Role wizard, set RAM Role Name to RamOssTest and Select Trusted Alibaba Cloud Account to Current Alibaba Cloud Account.

  4. Click OK. After the role is created, click Close.

  5. On the Roles page, enter RamOssTest in the search box, click the search icon, and click RamOssTest in the search result.

  6. Click Copy on the right side of the RamOssTest page to save the Alibaba Cloud Resource Name (ARN) of the role.arn

Step 4: Grant the role the permissions to upload objects to and download objects from OSS.

  1. Allow the RAM role to upload and download objects by attaching a custom policy to the RAM role.

    1. In the left-side navigation pane, choose Permissions > Policies.

    2. On the Policies page, click Create Policy.

    3. 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. The following sample code provides an example on how to grant the role the permissions.

      Warning

      The following example is only for reference. You must configure fine-grained RAM policies based on your requirements to prevent granting excessive permissions to users. For more information about how to configure fine-grained RAM policies, see Example 9: Use RAM or STS to authorize users to access OSS resources.

      {
          "Version": "1",
          "Statement": [
           {
                 "Effect": "Allow",
                 "Action": [
                   "oss:PutObject",
                   "oss:GetObject"
                 ],
                 "Resource": [
                   "acs:oss:*:*:examplebucket",
                   "acs:oss:*:*:examplebucket/*"
                 ]
           }
          ]
      }
    4. Click Next to edit policy information.

    5. In the Basic Information section, set Name to RamTestPolicy and click OK.

  2. Attach the custom policy to the RamOssTest role.

    1. In the left-side navigation pane, choose Identities > Roles.

    2. On the Roles page, find the RamOssTest role.

    3. Click Grant Permission in the Actions column.

    4. In the Grant Permission panel, select Custom Policy from the drop-down list in the Policy section and select the RamTestPolicy policy.

    5. Click Grant permissions.

Step 5: Generate temporary access credentials by using STS.

Temporary access credentials contain a security token and a temporary AccessKey pair. An AccessKey pair consists of an AccessKey ID and an AccessKey secret. The validity period of temporary access credentials is in seconds. 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.

Important

You must run the composer require alibabacloud/sts-20150401 command to install STS dependencies and run the composer require alibabacloud/sdk command to install OSS SDK for PHP dependencies before you obtain the temporary access credentials.

<?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 {
     // Before you run the sample code, make sure that you have configured the YOUR_ACCESS_KEY_ID and YOUR_ACCESS_KEY_SECRET environment variables by using the AccessKey pair of the RAM user that was created in Step 1. 
     $config = new Config([
       'accessKeyId' => getenv('YOUR_ACCESS_KEY_ID'),
       'accessKeySecret' => getenv('YOUR_ACCESS_KEY_SECRET'),
    ]);
    // 
    $config->endpoint = "sts.cn-hangzhou.aliyuncs.com";
    $client =  new Sts($config);   
        
    $assumeRoleRequest = new AssumeRoleRequest([
        // Specify the ARN of the RAM role that was created in Step 2. 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 based on the maximum session duration of the current role. 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 the 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;
    
    // Obtain access credentials from environment variables. 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. 
    $accessKeyId = getenv("OSS_ACCESS_KEY_ID");
    $accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
    $securityToken = getenv("OSS_SESSION_TOKEN");
    // 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 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;
    
    // Obtain access credentials from environment variables. 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. 
    $accessKeyId = getenv("OSS_ACCESS_KEY_ID");
    $accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
    $securityToken = getenv("OSS_SESSION_TOKEN");
    // 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 D:\\localpath as a local file named examplefile.txt. If a file that has the same name already exists in the path, the downloaded object overwrites the file. Otherwise, the downloaded object is saved in the path. 
    // If you do not specify a local path for the downloaded object, 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 object fails to be downloaded. If no exceptions are caught, the object is downloaded. 
    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 to authorize temporary access

Usage notes

  • When you use an OSS SDK to generate a signed URL, the OSS SDK uses a specific algorithm based on the key information stored in the local computer to calculate a signature and adds the signature to a URL to ensure the validity and security of the URL. The operations performed to calculate and construct the URL are completed on the client. You do not need to send requests to the server over the network. This way, you do not need to grant specific permissions to the caller when you generate the signed URL. However, to allow third-party users to perform relevant operations on the resources authorized by the signed URL, you must make sure that the principal that calls the API operations to generate the signed URL has the corresponding permissions.

    For example, if a principal wants to upload an object by using a signed URL, you must grant the oss:PutObject permission to the principal. If a principal wants to download or preview an object by using a signed URL, you must grant the oss:GetObject permission to the principal.

  • 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 specific data.

  • To generate a signed URL that is used to access resources over HTTPS, set the protocol in the endpoint to HTTPS.

  • The signed URL generated by using the following sample code may contain a plus sign (+). In this case, replace the plus sign (+) in the URL with %2B. Otherwise, the signed URL may not be used to access the object as expected.

Examples:

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;

// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
$accessKeyId = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// 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 the signed URL to 600 seconds (the maximum validity period is 32400s). 
$timeout = 600;
try{
  $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  $options = array(
      // Specify the version ID of the object. 
      $ossClient::OSS_VERSION_ID=>"CAEQEhiBgIDmgPf8mxgiIDA1YjZlNDIxY2ZmMzQ1MmU5MTM1Y2M4Yzk4NjIx****"
  );
  // Generate the 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 a local file

  1. 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;
    
    // Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    $accessKeyId = getenv("OSS_ACCESS_KEY_ID");
    $accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
    // 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 the signed URL to 600 seconds (the maximum validity period is 32400s). 
    $timeout = 600;
    try {
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);
    
        // Generate the 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");               
  2. Upload a local file 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

  1. 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;
    
    // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    $accessKeyId = getenv("OSS_ACCESS_KEY_ID");
    $accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
    // 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 the signed URL to 600 seconds (the maximum validity period is 32400s). 
    $timeout = 600;
    // A signed URL is generated to preview an object, and the custom domain name mapped to the bucket in which the object is stored is used for access. 
    $options= array(
        "response-content-disposition"=>"inline",);
    // Generate a signed URL to download the object. 
    /*$options = array(
        "response-content-disposition"=>"attachment",
    );*/
    try {
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);
        $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");               
  2. 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.