All Products
Search
Document Center

Object Storage Service:Authorize access

Last Updated:Mar 13, 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 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.

  • 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 and endpoints.

  • In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • 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 Initialization.

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.

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 = 'https://oss-cn-hangzhou.aliyuncs.com'
# Specify the AccessKey pair that is created for the RAM user in Step 1. 
access_key_id = 'yourAccessKeyId'
access_key_secret = 'yourAccessKeySecret'
# Specify the 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 the 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 = 'https://oss-cn-hangzhou.aliyuncs.com'
    # 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. Do not include the bucket name in the full path. 
    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(object_name, "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 = 'https://oss-cn-hangzhou.aliyuncs.com'
    # 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. Do not include the bucket name in the full path. 
    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 a visitor with the URL 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 specified data.

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.

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
from oss2.credentials import EnvironmentVariableCredentialsProvider
import requests

# 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. 
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())

# 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, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
# Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path. 
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. Set the validity period of the signed URL to 60. Unit: seconds. 
# By default, OSS identifies forward slashes (/) in the full path of an object as escape characters when a signed URL is generated. Therefore, the signed URL cannot be used directly. 
# 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. In this case, you can use the generated signed URL to upload the object. 
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
from oss2.credentials import EnvironmentVariableCredentialsProvider
import requests

# 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. 
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())

# 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, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
# Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path. 
object_name = 'exampledir/exampleobject.txt'

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

# Generate a signed URL that is used to upload the object. Set the validity period of the signed URL to 60. Unit: seconds. 
# By default, OSS identifies forward slashes (/) in the full path of an object as escape characters when a signed URL is generated. Therefore, the signed URL cannot be used directly. 
# 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. In this case, you can use the generated signed URL to upload the object. 
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 full 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
from oss2.credentials import EnvironmentVariableCredentialsProvider
import requests

# 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. 
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())

# 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, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
# Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path. 
object_name = 'exampledir/exampleobject.txt'

# Specify the headers. 
headers = dict()
# Specify Accept-Encoding. 
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 KB/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-t4nlw426y44rd3iq4xxxx"
# 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 forward slashes (/) in the full path of an object as escape characters when a signed URL is generated. Therefore, the signed URL cannot be used directly. 
# 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. In this case, you can use the generated signed URL to upload the object. 
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 full path of the local file. Example: D:\\exampledir\\examplefile.txt. 
with open("D:\\exampledir\\examplefile.txt", "wb") as code:
    code.write(resp.content)