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 the temporary access credentials that are provided by STS to 1,200 seconds and the validity period of the signed URL generated by using the credentials to 3,600 seconds. In this case, you cannot use the signed URL to upload objects after the temporary access credentials expire, even if the signed URL is within the 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 Initialization.

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.

  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. Specify the Logon Name and Display Name parameters.
  5. In the Access Mode section, select OpenAPI Access and click OK.
  6. 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, click Add Permissions in the Actions column corresponding to the created RAM user.
  2. In the Add Permissions panel, select the AliyunSTSAssumeRoleAccess policy from the policy list for System Policy. policy
  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. 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.
  6. Click Copy on the right 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 the bucket named examplebucket. 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/*"
                 ]
           }
          ]
      }
    4. Click Next Step.
    5. In the Basic Information section, set Policy 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 corresponding to the RamOssTest role.
    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.

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.

For the complete sample code, visit GitHub.

Important Run the pip install aliyun-python-sdk-sts command to install the official STS client for Python before you obtain the temporary access credentials.
# -*- coding: utf-8 -*-

from aliyunsdkcore import client
from aliyunsdkcore.request import CommonRequest
import json
import oss2

# 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 AccessKey pair that is created for the RAM user in Step 1. 
access_key_id = 'yourAccessKeyId'
access_key_secret = 'yourAccessKeySecret'
// Specify the Alibaba Cloud Resource Name (ARN) of the role that is created in Step 3. Example: acs:ram::175708322470****:role/ramtest. 
role_arn = 'acs:ram::175708322470****:role/ramtest'

# Create a RAM policy. 
# The policy specifies that the PutObject and GetObject operations can be performed only on resources in the bucket named examplebucket. 
policy_text = '{"Version": "1", "Statement": [{"Action": ["oss:PutObject","oss:GetObject"], "Effect": "Allow", "Resource": ["acs:oss:*:*:examplebucket/*"]}]}'

clt = client.AcsClient(access_key_id, access_key_secret, 'cn-hangzhou')
request = CommonRequest(product="Sts", version='2015-04-01', action_name='AssumeRole')
request.set_method('POST')
request.set_protocol_type('https')
request.add_query_param('RoleArn', role_arn)
# Specify a custom role session name to distinguish different tokens. Example: sessiontest. 
request.add_query_param('RoleSessionName', 'sessiontest')
# Specify the validity period of temporary access credentials. Unit: seconds. Valid values: 900 to 3600. 
request.add_query_param('DurationSeconds', '3000')
# If you do not specify the RAM policy, the RAM user is granted all permissions of the role. If you have specific requirements on the permissions, refer to the preceding configurations of policy_text. 
request.add_query_param('Policy', policy_text)
request.set_accept_format('JSON')

body = clt.do_action_with_exception(request)

# Use the AccessKey pair of the RAM user to apply for temporary access credentials from STS. 
token = json.loads(oss2.to_unicode(body))
# Display the AccessKey ID, the AccessKey secret, the security token, and the expiration time of the temporary access credentials returned by STS. 
print('AccessKeyId: '+token['Credentials']['AccessKeyId'])
print('AccessKeySecret: '+token['Credentials']['AccessKeySecret'])
print('SecurityToken: '+token['Credentials']['SecurityToken'])
print('Expiration: '+token['Credentials']['Expiration'])

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
    # -*- coding: utf-8 -*-
    import oss2
    
    # 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 temporary AccessKey pair obtained from STS. 
    sts_access_key_id = 'yourAccessKeyId'
    sts_access_key_secret = 'yourAccessKeySecret'
    # Specify the name of the bucket. 
    bucket_name = 'examplebucket'
    # Specify the full path of the object and the string that you want to upload. The full path of the object cannot contain the bucket name. 
    object_name = 'exampleobject.txt'
    # Specify the security token obtained from STS. 
    security_token = 'yourSecurityToken'
    
    
    # Initialize the StsAuth instance based on the authentication information in the temporary access credentials. 
    auth = oss2.StsAuth(sts_access_key_id,
                        sts_access_key_secret,
                        security_token)
    
    # Initialize the bucket based on the StsAuth instance. 
    bucket = oss2.Bucket(auth, endpoint, bucket_name)
    
    # Upload the object. 
    result = bucket.put_object('example-test.txt', "hello world")
    print(result.status)
  • Use the temporary access credentials to download objects from OSS
    # -*- coding: utf-8 -*-
    import oss2
    
    # 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 temporary AccessKey pair obtained from STS. 
    sts_access_key_id = 'yourAccessKeyId'
    sts_access_key_secret = 'yourAccessKeySecret'
    # Specify the name of the bucket. Example: examplebucket. 
    bucket_name = 'examplebucket'
    # Specify the full path of the object and the string that you want to download. The full path of the object cannot contain the bucket name. 
    object_name = 'exampleobject.txt'
    # Specify the security token obtained from STS. 
    security_token = 'yourSecurityToken'
    
    # Initialize the StsAuth instance based on the authentication information in the temporary access credentials. 
    auth = oss2.StsAuth(sts_access_key_id,
                        sts_access_key_secret,
                        security_token)
    
    # Initialize the bucket based on the StsAuth instance. 
    bucket = oss2.Bucket(auth, endpoint, bucket_name)
    
    # Download the object. 
    read_obj = bucket.get_object(object_name)
    print(read_obj.read())

Use a signed URL for temporary access authorization

The following section provides examples on how to use a signed URL to authorize temporary access to OSS.

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 the object.

Important If you use the following code to generate a signed URL that contains the plus sign (+), you may fail to access OSS by using the URL. In this case, you must replace the plus sign (+) in the URL with %2B.

You can add signature information to a URL and provide the URL to a third-party user for authorized access. For more information, see Add signatures to URLs.

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:

# -*- coding: utf-8 -*-
import oss2
import requests

# 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. 
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# If you use STS authorization, specify the temporary AccessKey pair and the security token that you obtained from STS. 
# auth = oss2.StsAuth('yourAccessKeyId', 'yourAccessKeySecret', 'yourToken')

# 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 the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, 'yourEndpoint', 'examplebucket')
# Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name. 
object_name = 'exampledir/exampleobject.txt'

# Specify the headers. 
headers = dict()
# Specify the version ID of the object. 
headers["versionId"] = "CAEQARiBgID8rumR2hYiIGUyOTAyZGY2MzU5MjQ5ZjlhYzQzZjNlYTAyZDE3****"

# Generate a signed URL that is used to upload the object. The validity period of the URL is 60 seconds. 
# By default, OSS identifies the forward slashes (/) in the full path of an object as escape characters when the signed URL is generated. Therefore, you cannot directly use the signed URL. 
# Set the slash_safe parameter to True. This way, OSS does not identify the forward slashes (/) in the full path of the object as escape characters. Then, you can directly use the generated signed URL. 
url = bucket.sign_url('PUT', object_name, 60, slash_safe=True, headers=headers)
print('The signed URL:', url)

Use a signed URL to upload an object

The following sample code provides an example on how to use a signed URL to upload an object:

# -*- coding: utf-8 -*-
import oss2
import requests

# 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. 
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# If you use STS authorization, specify the temporary AccessKey pair and the security token that you obtained from STS. 
# auth = oss2.StsAuth('yourAccessKeyId', 'yourAccessKeySecret', 'yourToken')

# 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 the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, 'yourEndpoint', 'examplebucket')
# Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name. 
object_name = 'exampledir/exampleobject.txt'

# Specify the headers. 
headers = dict()
# Specify the Content-Type parameter. 
# headers['Content-Type'] = 'text/txt'
# Specify the storage class. 
# headers["x-oss-storage-class"] = "Standard"

# Generate a signed URL that is used to upload the object. The validity period of the URL is 60 seconds. 
# By default, OSS identifies the forward slashes (/) in the full path of an object as escape characters when the signed URL is generated. Therefore, you cannot directly use the signed URL. 
# Set the slash_safe parameter to True. This way, OSS does not identify the forward slashes (/) in the full path of the object as escape characters. Then, you can directly use the generated signed URL. 
url = bucket.sign_url('PUT', object_name, 60, slash_safe=True, headers=headers)
print('The signed URL:', url)

# Use the signed URL to upload an object. requests is used as an example. 
# Specify the path of the local file. Example: D:\\exampledir\\examplefile.txt. 
requests.put(url, data=open('D:\\exampledir\\examplefile.txt', 'rb').read(), headers=headers)       

Use a signed URL to download an object

The following sample code provides an example on how to use the signed URL to download an object:

# -*- coding: utf-8 -*-
import oss2
import requests

# 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. 
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# If you use STS authorization, specify the temporary AccessKey pair and the security token that you obtained from STS. 
# auth = oss2.StsAuth('yourAccessKeyId', 'yourAccessKeySecret', 'yourToken')

# 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 the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, 'yourEndpoint', 'examplebucket')
# Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name. 
object_name = 'exampledir/exampleobject.txt'

# Specify the headers. 
headers = dict()
# Specify the Accept-Encoding parameter. 
headers['Accept-Encoding'] = 'gzip'

# Specify HTTP query parameters. 
params = dict()
# Configure single-connection bandwidth throttling. Unit: bit/s. In this example, the maximum bandwidth is set to 100 Kbit/s. 
# params['x-oss-traffic-limit'] = str(100 * 1024 * 8)
# Specify the IP address or CIDR block. 
# params['x-oss-ac-source-ip'] = "127.0.0.1"
# Specify the number of the digit 1 in the subnet mask. 
# params['x-oss-ac-subnet-mask'] = "32"
# Specify the ID of the virtual private cloud (VPC). 
# params['x-oss-ac-vpc-id'] = "vpc-t4nlw426y44rd3iq4****"
# Specify whether the request can be forwarded. 
# params['x-oss-ac-forward-allow'] = "true"

# Generate a signed URL that is used to download the object. The validity period of the URL is 60 seconds. 
# By default, OSS identifies the forward slashes (/) in the full path of an object as escape characters when the signed URL is generated. Therefore, you cannot directly use the signed URL. 
# Set the slash_safe parameter to True. This way, OSS does not identify the forward slashes (/) in the full path of the object as escape characters. Then, you can directly use the generated signed URL. 
url = bucket.sign_url('GET', object_name, 60, slash_safe=True, headers=headers, params=params)
print('The signed URL:', url)

# Use the signed URL to download the object. requests is used as an example. 
resp = requests.get(url, headers=headers)

# Specify the path of the local file. Example: D:\\exampledir\\examplefile.txt. 
with open("D:\\exampledir\\examplefile.txt", "wb") as code:
    code.write(resp.content)