このトピックでは、ユーザーへのアクセスを許可する方法について説明します。
一時的アクセスを許可するための URL に署名
一時的アクセスのために訪問者に対して、署名された URL を提供することができます。 URL に署名する際、訪問者からのアクセス期間を制限するため、URL の有効期限を指定できます。
署名付き URL を持つオブジェクトをダウンロードするには、次のコードを実行します。
# -*- coding: utf-8 -*-
import oss2
# It is highly risky to log on with AccessKey of an Alibaba Cloud account because the account has permissions on all APIs in OSS. We recommend that you log on as a RAM user to access APIs or perform routine operations and maintenance. To create a RAM account, log on to https://ram.console.aliyun.com.
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
# This example uses endpoint China (Hangzhou). Specify the actual endpoint based on your requirements.
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')
# Set the expiration time of the URL to one hour.
print(bucket.sign_url('GET', '<yourObjectName>', 60))
STS を使用した一時的アクセス許可
STS を使用する完全なコードについては、『GitHub』をご参照ください。
一時的なアクセス許可には、STS (Security Token Service) を使用できます。 STS の詳細については、STS アクセスコントロール API の「はじめに」をご参照ください。 アカウントと承認の詳細については、「ベストプラクティス」内の「STS 一時的アクセス許可」をご参照ください。
公式の Python STS クライアントをインストールする必要があります。
pip install aliyun-python-sdk-sts
バージョン 2.0.5 またはそれ以降のバージョンをお使いください。 次のコードを実行し、STS で署名リクエストを作成します。
# -*- coding: utf-8 -*-
from aliyunsdkcore import client
from aliyunsdksts.request.v20150401 import AssumeRoleRequest
import json
import oss2
# This example uses endpoint China (Hangzhou). Specify the actual endpoint based on your requirements.
endpoint = 'oss-cn-hangzhou.aliyuncs.com'
# It is highly risky to log on with AccessKey of an Alibaba Cloud account because the account has permissions on all APIs in OSS. We recommend that you log on as a RAM user to access APIs or perform routine operations and maintenance. To create a RAM account, log on to https://ram.console.aliyun.com.
access_key_id = '<yourAccessKeyId>'
access_key_secret = '<yourAccessKeySecret>'
bucket_name = '<yourBucketName>'
# role_arn is the resource name of the role.
role_arn = '<yourRoleArn>'
clt = client.AcsClient(access_key_id, access_key_secret, 'cn-hangzhou')
req = AssumeRoleRequest.AssumeRoleRequest()
# Set the format of returned values to JSON.
req.set_accept_format('json')
req.set_RoleArn(role_arn)
req.set_RoleSessionName('session-name')
body = clt.do_action(req)
# Use the AccessKeyId and AccessKeySecret to apply for a temporary token from STS.
token = json.loads(body)
# Use the authentication information in the temporary token to initialize the StsAuth instance.
auth = oss2.StsAuth(token['Credentials']['AccessKeyId'],
token['Credentials']['AccessKeySecret'],
token['Credentials']['SecurityToken'])
# Use the StsAuth instance to initialize the bucket.
bucket = oss2.Bucket(auth, endpoint, bucket_name)
# Upload a string.
bucket.put_object('object-name.txt', b'hello world')