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

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 an access credential that has a custom validity period and custom permissions for a third-party application or a Resource Access Management (RAM) user managed by you. For more information about STS, see What is STS?.

STS has the following benefits:

  • You need only to generate an access token and send the access token to a third-party application, instead of exposing your AccessKey pair to the third-party application. You can customize the access permissions and validity period of this token.
  • The access token automatically expires after the validity period. Therefore, you do not need to manually revoke the permissions of an access 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 a temporary access credential. The temporary access credential contains a security token and a temporary AccessKey pair that consists of an AccessKey ID and an AccessKey secret. The minimum validity period of a temporary access credential is 900 seconds. The maximum validity period of a temporary access credential is the maximum session duration specified by 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 Security Token Service (STS) client for Python. For the complete sample code of STS usage, visit GitHub.

Make sure that you use Object Storage Service (OSS) SDK for Python V2.0.6 and later. The following code provides an example on how to use STS to temporarily download an object:

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

from aliyunsdkcore import client
from aliyunsdksts.request.v20150401 import AssumeRoleRequest
import json
import oss2

# Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = 'yourEndpoint'
# Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. 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 of the object cannot contain bucket names. 
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 indicates the Alibaba Cloud account ID. To view the Alibaba Cloud account ID, perform the following steps: Log on to the OSS console, and 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 indicates 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, click Roles. On the page that appears, 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 on resources only 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)
# Set the RoleSessionName parameter. This parameter can be used to identify the RAM user who assumes the RAM role. 
req.set_RoleSessionName('session-name')
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 based on the authentication information in the temporary access credential. 
auth = oss2.StsAuth(token['Credentials']['AccessKeyId'],
                    token['Credentials']['AccessKeySecret'],
                    token['Credentials']['SecurityToken'])

# Initialize a bucket based on 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 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 access from visitors. By default, the validity period of a signed URL is 3,600 seconds. The maximum validity period of a signed URL is 32,400 seconds.

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

Note The validity period must be set for an STS temporary account and a signed URL. When you use an STS temporary account 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 STS temporary account to 1200 seconds, and that of the signed URL to 3600 seconds. You cannot use the signed URL generated by the STS temporary account to upload objects 1200 seconds after the account is generated.
  • Use a signed URL to temporarily upload an object

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

    # -*- coding: utf-8 -*-
    import oss2
    
    # Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. 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')
    # Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint 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 bucket names. 
    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 the 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 so that 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 is: ', url)
    
    # Use the signed URL to upload an object. 
    # Specify the full path of the local file that you want 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 temporarily download an object

    The following code provides an example on how to use a signed URL to temporarily download an object:

    # -*- coding: utf-8 -*-
    import oss2
    # Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. 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')
    # Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint 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 bucket names. 
    object_name = 'exampledir/exampleobject.txt'
    
    # 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 the 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 so that 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)     
    print (the address of the signed URL is: ', url)
    
    # Use the signed URL to download the object to the local path. 
    # Specify the full path of the local file downloaded from OSS. 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())