All Products
Search
Document Center

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

Last Updated:Jan 23, 2024

This topic describes how to authorize temporary access to Object Storage Service (OSS) by using Security Token Service (STS) and a signed URL, respectively.

Usage notes

  • Validity periods 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 shorter 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 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 STS to authorize temporary access to OSS. STS is a web service that provides temporary access tokens. 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 has 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 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

  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. On the page that appears, click Copy to save the AccessKey pair of the RAM user.

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 Add Permissions panel, click the System Policy tab and select the AliyunSTSAssumeRoleAccess policy.image.png

  3. Click OK.

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 Create Role panel, set Select Trusted Entity to Alibaba Cloud Account and click Next.

  3. In the Create Role panel, 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 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. Grant the role the permissions to upload objects to and download objects from a bucket by using custom policies.

    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 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. You must configure fine-grained RAM policies based on your requirements to avoid 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 Add Permissions in the Actions column.

    4. In the Add Permissions panel, click the Custom Policy tab and select the RamTestPolicy policy.

    5. Click OK.

Step 5: Generate temporary access credentials by using STS

Temporary access credentials contain a security token and a temporary AccessKey pair that 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.

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 Alibaba Cloud Resource Name (ARN) of the role that was 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 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 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 of the object. 
    $object = "exampleobject.txt";
    // Specify the string that you want to upload as an object. 
    $content = "Hello OSS";
    
    try {
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken);
        // Upload the string to 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;
    
    // 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 of the object. 
    $object = "exampleobject.txt";
    // Download the object to the local path D:\\localpath as a local file named examplefile.txt. If a file that has 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 a 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 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 third-party user 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 that is used to authorize access, visit GitHub.

Important

The signed URL generated by using the following sample code may contain a plus sign (+). In this case, you must replace the plus sign (+) in the URL with %2B. Otherwise, the signed URL may be inaccessible.

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 of the object. 
$object = "exampleobject.txt";
// Set the validity period of the 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 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 URL to upload 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;
    
    // 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 of the object. 
    $object = "exampleobject.txt";
    // Set the validity period of the signed URL to 3,600 seconds. 
    $timeout = 3600;
    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 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

  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 of the object. 
    $object = "exampleobject.txt";
    // Set the validity period of the signed URL to 3,600 seconds. 
    $timeout = 3600;
    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 that is used 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.