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.

Notice 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, even if the signed URL is within its validity period.

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 a set of temporary access credentials that have a custom validity period and custom permissions to a third-party application or a RAM user managed by you. For more information about STS, see What is STS?

STS provides the following benefits:

  • You need only to 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 validity period of this token.
  • The token automatically expires after the validity period. Therefore, you do not need to manually revoke the access permissions of a token.
Note For more information about how to configure STS, see Use a temporary credential provided by STS to access OSS in OSS Developer Guide. You can call the AssumeRole operation or use STS SDKs for various programming languages to obtain temporary access credentials from STS. For more information, see STS SDK overview. The temporary access credentials consist of a temporary 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.

Run the pip install aliyun-python-sdk-sts command to install the official STS client for Python. For more information about the complete sample code, visit GitHub.

Make sure that you use OSS SDK for Python V2.0.6 or later. The following code provides an example on how to use a temporary access credential obtained from STS to download an object:

# -*- coding: utf-8 -*-

from aliyunsdkcore import client
from aliyunsdksts.request.v20150401 import AssumeRoleRequest
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'
# 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 Resource Access Management (RAM) user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
access_key_id = 'yourAccessKeyId'
access_key_secret = 'yourAccessKeySecret'
# Specify the name of the bucket. Example: examplebucket. 
bucket_name = 'examplebucket'
# Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path cannot contain the bucket name. 
object_name = 'exampledir/exampleobject.txt'
# To obtain the Alibaba Cloud Resource Name (ARN) information of the RAM role, log on to the RAM console. In the left-side navigation pane, choose Identities > Roles. On the Roles page, search for and click the created RAM role. In the Basic Information section of the role details page, you can view and copy the ARN information. 
# Specify the ARN information of the RAM role. Format: acs:ram::$accountID:role/$roleName. 
# $accountID specifies the Alibaba Cloud account ID. To view the Alibaba Cloud account ID, perform the following steps: Log on to the OSS console. Move the pointer over the profile picture in the upper-right corner to view and copy the account ID, or click Basic Information to view the account ID. 
# $roleName specifies the name of the RAM role. To view the RAM role name, perform the following steps: Log on to the RAM console. In the left-side navigation pane, choose Identities > Roles. On the Roles page, view the name in the Role Name column. 
role_arn = 'acs:ram::17464958********:role/ossststest'

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

clt = client.AcsClient(access_key_id, access_key_secret, 'cn-hangzhou')
req = AssumeRoleRequest.AssumeRoleRequest()

# Set the format of the returned value to JSON. 
req.set_accept_format('json')
req.set_RoleArn(role_arn)
# Specify a custom role session name to distinguish different tokens. Example: session-test. 
req.set_RoleSessionName('session-test')
req.set_Policy(policy_text)
body = clt.do_action_with_exception(req)

# Use the AccessKey pair of the RAM user to apply for a temporary access credential from STS. 
token = json.loads(oss2.to_unicode(body))

# Initialize the StsAuth instance with the authentication information in the temporary access credential. 
auth = oss2.StsAuth(token['Credentials']['AccessKeyId'],
                    token['Credentials']['AccessKeySecret'],
                    token['Credentials']['SecurityToken'])

# Initialize a bucket with the StsAuth instance. 
bucket = oss2.Bucket(auth, endpoint, bucket_name)

# Download the object from the bucket. 
read_obj = bucket.get_object(object_name)
print(read_obj.read())            

Use a signed URL for temporary access authorization

This section provides examples on how to use a signed URL to authorize temporary access.

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.

Notice 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.

  • Use a signed URL to upload an object

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

    # -*- coding: utf-8 -*-
    import oss2
    
    # 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 Resource Access Management (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')
    # 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 cannot contain the bucket name. 
    object_name = 'exampledir/exampleobject.txt'
    
    # 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) 
    print('the address of the signed URL:', url)
    
    # Use the signed URL to upload a local file. 
    # Specify the full path of the local file to upload. Example: D:\\localpath\\examplefile.txt. 
    # By default, if you set this parameter to the name of a local file such as examplefile.txt without specifying the local path, the local file is uploaded from the local path of the project to which the sample program belongs. 
    result = bucket.put_object_with_url_from_file(url, 'D:\\localpath\\examplefile.txt')
    print(result.status)         
  • Use a signed URL to obtain an object

    The following code provides an example on how to use a signed URL with temporary authorization to download or preview an object:

    # -*- coding: utf-8 -*-
    import oss2
    # 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 Resource Access Management (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')
    # 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 cannot contain the bucket name. 
    object_name = 'exampledir/exampleobject.txt'
    
    # Specify a header. 
    headers = dict()
    # To implement automatic download when the object is accessed by using a browser and specify the name of the downloaded object, set the Content-Disposition header in the configuration file to attachment.
    # headers['content-disposition'] = 'attachment'
    # To preview the object when you use the signed URL to access the object in a browser, set the Content-Disposition header to inline and use the custom domain name that is mapped to the bucket to access the object. 
    headers['content-disposition'] = 'inline'
    
    # Generate the 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, headers=headers, slash_safe=True)
    print('the address of the signed URL:', url)
    
    # Use the signed URL to download the object to a local path. 
    # Specify the full path of the local file to upload. Example: D:\\localpath\\examplefile.txt. 
    # By default, if you set this parameter to the name of a local file such as examplefile.txt without specifying the local path, the downloaded object is saved to the local path of the project to which the sample program belongs. 
    result = bucket.get_object_with_url_to_file(url, 'D:\\localpath\\examplefile.txt')
    print(result.read())