Before you can use the Python software development kit (SDK) to send requests to Object Storage Service (OSS), you must configure access credentials. Alibaba Cloud services use access credentials to verify your identity and permissions. You can select a type of access credential based on the authentication and authorization requirements of your scenario.
Usage notes
For more information about the mapping between OSS regions and endpoints, see Regions and endpoints.
For more information about how to create an AccessKey pair for a Resource Access Management (RAM) user, see Create an AccessKey pair.
Before you configure access credentials, install the latest version of the OSS Python SDK. For more information, see Installation (Python SDK V1).
Ensure that the alibabacloud-credentials version is 0.3.5 or later. Earlier versions may cause errors.
Select a credential provider
OSS supports multiple methods for initializing a credential provider. You can select an initialization method based on the authentication and authorization requirements of your scenario.
Credential Provider Initialization Methods | Scenario | AccessKey pair or STS token required | Underlying credential | Credential validity period | Credential rotation or refresh method |
Applications are deployed and run in a secure and stable environment that is not vulnerable to external attacks, and need long-term access to Alibaba Cloud services without frequent credential rotation. | Yes | AK | Long-term | Manual rotation | |
Applications are deployed and run in an untrusted environment, in which case you want to control the credential validity period and permissions. | Yes | Security Token Service (STS) token | Temporary | Manual refresh | |
Applications require authorization to access Alibaba Cloud services, such as cross-account access to Alibaba Cloud services. | Yes | STS token | Temporary | Auto-refresh | |
Applications are deployed and run on Alibaba Cloud ECS instances, ECI instances, or Container Service for Kubernetes worker nodes. | No | STS token | Temporary | Auto-refresh | |
Untrusted applications are deployed and run on Alibaba Cloud Container Service for Kubernetes worker nodes. | No | STS token | Temporary | Auto-refresh | |
Functions of applications are deployed and run in Alibaba Cloud Function Compute. | No | STS token | Temporary | No refresh required | |
Applications need to obtain access credentials from an external system. | No | STS token | Temporary | Auto-refresh | |
Applications are deployed in an environment where AccessKey pairs are at risk of being leaked and require frequent credential rotation for long-term access to Alibaba Cloud services. | No | AK | Long-term | Automatic rotation | |
If none of the preceding credential configuration methods meet your requirements, you can customize a method to obtain credentials. | Custom | Custom | Custom | Custom |
Common configuration examples
Use the AccessKey pair of a RAM user
You can use the AccessKey pair (AccessKey ID and AccessKey secret) of an Alibaba Cloud account or a RAM user to initialize the credential provider. This method is suitable if your application is deployed in a secure and stable environment, is not vulnerable to external attacks, requires long-term access to OSS, and does not allow for frequent credential rotation. This method requires you to manually maintain an AccessKey pair, which poses security risks and increases maintenance complexity.
An Alibaba Cloud account has full permissions on its resources. If the AccessKey pair of the account is leaked, your system is exposed to significant security risks. We do not recommend using the AccessKey pair of an Alibaba Cloud account. Instead, use the AccessKey pair of a RAM user with the minimum required permissions.
For information about how to create an AccessKey pair for a RAM user, see Create an AccessKey pair. The AccessKey ID and AccessKey secret of a RAM user are displayed only when they are created. You must save them immediately. If you forget them, you must create a new AccessKey pair for rotation.
Environment variables
You can configure environment variables using the AccessKey pair of a RAM user.
Linux
In the command-line interface, run the following command to append the environment variable settings to the
~/.bashrc
file.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
Run the following command to apply the changes.
source ~/.bashrc
Run the following commands to check whether the environment variables are configured.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
In the terminal, run the following command to view the default shell type.
echo $SHELL
Perform the required operations based on the default shell type.
Zsh
Run the following commands to append the environment variable settings to the
~/.zshrc
file.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
Run the following command to apply the changes.
source ~/.zshrc
Run the following commands to check whether the environment variables are configured.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
Run the following commands to append the environment variable settings to the
~/.bash_profile
file.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
Run the following command to apply the changes.
source ~/.bash_profile
Run the following commands to check whether the environment variables are configured.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Windows
CMD
Run the following commands in the Command Prompt.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
Run the following commands to check whether the environment variables are configured.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
Run the following commands in PowerShell.
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
Run the following commands to check whether the environment variables are configured.
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
After you modify the system environment variables, restart or refresh your development and runtime environment. This includes your IDE, command-line interface, other desktop applications, and backend services. This ensures that the latest system environment variables are loaded.
You can pass credential information using environment variables.
# -*- coding: utf-8 -*- import oss2 from oss2.credentials import EnvironmentVariableCredentialsProvider # 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 the endpoint to https://oss-cn-hangzhou.aliyuncs.com. endpoint = 'https://oss-cn-hangzhou.aliyuncs.com' # Set yourBucketName to the name of the bucket. bucket_name = 'yourBucketName' # Set the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. region = 'cn-hangzhou' # Configure access credentials using the AccessKey pair of the RAM user obtained from the environment variables. Note that ProviderAuthV4 indicates that Signature V4 is used. auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) # Initialize the bucket using the Auth instance. Note that when you use Signature V4, you must specify the region parameter. Otherwise, an error is reported. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # Use the bucket object for subsequent operations.
Static credentials
The following sample code shows how to hard-code access credentials and explicitly set the AccessKey pair.
Do not embed access credentials in applications in a production environment. This method is intended for testing purposes only.
# -*- coding: utf-8 -*-
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 the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# Set yourBucketName to the name of the bucket.
bucket_name = 'yourBucketName'
# Set the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
region = 'cn-hangzhou'
# Enter the AccessKey ID and AccessKey secret of the RAM user.
access_key_id = 'yourAccessKeyID'
access_key_secret = 'yourAccessKeySecret'
# Configure access credentials using the AccessKey pair of the RAM user. Note that AuthV4 indicates that Signature V4 is used.
auth = oss2.AuthV4(access_key_id, access_key_secret)
# Initialize the bucket using the Auth instance. Note that when you use Signature V4, you must specify the region parameter. Otherwise, an error is reported.
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
# Use the bucket object for subsequent operations.
Use a temporary access credential from STS
If your application requires temporary access to OSS, you can use a temporary identity credential (AccessKey ID, AccessKey secret, and Security Token) obtained from STS to initialize the credential provider. This method requires you to manually maintain an STS token, which poses security risks and increases maintenance complexity. In addition, if you require temporary access to OSS multiple times, you must manually refresh the STS token.
To quickly and easily obtain a temporary access credential from STS using OpenAPI, see AssumeRole - Obtain a temporary identity credential for a RAM role.
To obtain a temporary access credential from STS using an SDK, see Use an STS token to access OSS.
You must specify an expiration time when you generate an STS token. The token automatically becomes invalid after it expires and cannot be used again.
For a list of STS endpoints, see Endpoints.
Environment variables
You can set environment variables using the temporary identity credential.
Mac OS X/Linux/Unix
WarningUse the temporary identity credential (AccessKey ID, AccessKey secret, and Security Token) obtained from STS, not the AccessKey pair of the RAM user.
The AccessKey ID obtained from STS starts with STS, for example, "STS.****************".
export OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID> export OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET> export OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>
Windows
WarningUse the temporary identity credential (AccessKey ID, AccessKey secret, and Security Token) obtained from STS, not the AccessKey pair (AccessKey ID and AccessKey secret) of the RAM user.
The AccessKey ID obtained from STS starts with STS, for example, "STS.****************".
set OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID> set OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET> set OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>
You can pass credential information using environment variables.
# -*- coding: utf-8 -*- import oss2 from oss2.credentials import EnvironmentVariableCredentialsProvider # 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 the endpoint to https://oss-cn-hangzhou.aliyuncs.com. endpoint = 'https://oss-cn-hangzhou.aliyuncs.com' # Set yourBucketName to the name of the bucket. bucket_name = 'yourBucketName' # Set the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. region = 'cn-hangzhou' # Configure access credentials using the STS AccessKey ID, AccessKey secret, and Security Token obtained from the environment variables. Note that ProviderAuthV4 indicates that Signature V4 is used. auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) # Initialize the bucket using the Auth instance. Note that when you use Signature V4, you must specify the region parameter. Otherwise, an error is reported. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # Use the bucket object for subsequent operations.
Static credentials
The following sample code shows how to hard-code access credentials and explicitly set the temporary AccessKey pair.
Do not embed access credentials in applications in a production environment. This method is intended for testing purposes only.
# -*- coding: utf-8 -*-
import oss2
# Enter the temporary AccessKey ID and AccessKey secret, not the AccessKey ID and AccessKey secret of an Alibaba Cloud account.
# Note that the AccessKey ID obtained from STS starts with STS, as shown in the following example.
sts_access_key_id = 'STS.****************'
sts_access_key_secret = 'yourAccessKeySecret'
# Enter the STS token obtained from STS.
security_token = 'yourSecurityToken'
# 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 the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# Set yourBucketName to the name of the bucket.
bucket_name = 'yourBucketName'
# Set the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
region = 'cn-hangzhou'
# Initialize the StsAuth instance. Note that auth_version is set to "v4", which indicates that OSS Signature V4 is used.
auth = oss2.StsAuth(sts_access_key_id,
sts_access_key_secret,
security_token,
auth_version="v4")
# Initialize the bucket using the StsAuth instance. Note that when you use Signature V4, you must specify the region parameter. Otherwise, an error is reported.
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
# Use the bucket object for subsequent operations.
More configuration examples
Use a RAMRoleARN
If your application requires authorization to access OSS, such as for cross-account access, you can use a RAMRoleARN to initialize the credential provider. The underlying implementation of this method is an STS token. By specifying the Alibaba Cloud Resource Name (ARN) of a RAM role, the Credentials tool obtains an STS token from STS. The tool then requests a new STS token by calling the AssumeRole operation before the session expires. In addition, you can assign a value to the policy
parameter to restrict the RAM role to a smaller set of permissions.
An Alibaba Cloud account has full permissions on its resources. If the AccessKey pair of the account is leaked, your system is exposed to significant security risks. We do not recommend using the AccessKey pair of an Alibaba Cloud account. Instead, use the AccessKey pair of a RAM user with the minimum required permissions.
For information about how to create an AccessKey pair for a RAM user, see Create an AccessKey pair. The AccessKey ID and AccessKey secret of a RAM user are displayed only when they are created. You must save them immediately. If you forget them, you must create a new AccessKey pair for rotation.
To obtain a RAMRoleARN, see CreateRole - Create a RAM role.
You can add the alibabacloud_credentials dependency.
pip install alibabacloud_credentials
You can configure the AccessKey pair and RAMRoleARN as access credentials.
# -*- coding: utf-8 -*- import oss2 from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config from oss2 import CredentialsProvider from oss2.credentials import Credentials import os class CredentialProviderWrapper(CredentialsProvider): def __init__(self, client): self.client = client def get_credentials(self): credential = self.client.get_credential() access_key_id = credential.access_key_id access_key_secret = credential.access_key_secret security_token = credential.security_token return Credentials(access_key_id, access_key_secret, security_token) config = Config( # Obtain the AccessKey pair (AccessKey ID and AccessKey secret) of the RAM user from environment variables. access_key_id=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'), access_key_secret=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), type='ram_role_arn', # The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole. You can set RoleArn using the ALIBABA_CLOUD_ROLE_ARN environment variable. role_arn='<RoleArn>', # The name of the role session. You can set RoleSessionName using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. role_session_name='<RoleSessionName>', # Set a smaller permission policy. This parameter is optional. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"} policy='<Policy>', # Set the validity period of the role session. This parameter is optional. role_session_expiration=3600 ) cred = Client(config) credentials_provider = CredentialProviderWrapper(cred) # Note that ProviderAuthV4 indicates that Signature V4 is used. auth = oss2.ProviderAuthV4(credentials_provider) # 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 the endpoint to https://oss-cn-hangzhou.aliyuncs.com. endpoint = 'https://oss-cn-hangzhou.aliyuncs.com' # Set yourBucketName to the name of the bucket. bucket_name = 'yourBucketName' # Set the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. region = 'cn-hangzhou' # Initialize the bucket using the Auth instance. Note that when you use Signature V4, you must specify the region parameter. Otherwise, an error is reported. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # Use the bucket object for subsequent operations.
Use an ECSRAMRole
If your application runs on an ECS instance, an ECI instance, or a Container Service for Kubernetes worker node, we recommend that you use an ECSRAMRole to initialize the credential provider. The underlying implementation of this method is an STS token. An ECSRAMRole lets you associate a role with an ECS instance, an ECI instance, or a Container Service for Kubernetes worker node to automatically refresh the STS token within the instance. This method does not require you to provide an AccessKey pair or an STS token. This eliminates the risks of manual maintenance. For information about how to obtain an ECSRAMRole, see CreateRole - Create a RAM role.
You can add the alibabacloud_credentials dependency.
pip install alibabacloud_credentials
You can configure an ECSRAMRole as the access credential.
# -*- coding: utf-8 -*- import oss2 from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config from oss2 import CredentialsProvider from oss2.credentials import Credentials class CredentialProviderWrapper(CredentialsProvider): def __init__(self, client): self.client = client def get_credentials(self): credential = self.client.get_credential() access_key_id = credential.access_key_id access_key_secret = credential.access_key_secret security_token = credential.security_token return Credentials(access_key_id, access_key_secret, security_token) config = Config( type='ecs_ram_role', # The type of the access credential. Set the value to ecs_ram_role. role_name='<RoleName>' # The name of the RAM role granted to the ECS instance. This parameter is optional. If you do not set this parameter, the role is automatically retrieved. We recommend that you set this parameter to reduce requests. ) cred = Client(config) credentials_provider = CredentialProviderWrapper(cred) # Note that ProviderAuthV4 indicates that Signature V4 is used. auth = oss2.ProviderAuthV4(credentials_provider) # 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 the endpoint to https://oss-cn-hangzhou.aliyuncs.com. endpoint = 'https://oss-cn-hangzhou.aliyuncs.com' # Set yourBucketName to the name of the bucket. bucket_name = 'yourBucketName' # Set the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. region = 'cn-hangzhou' # Initialize the bucket using the Auth instance. Note that when you use Signature V4, you must specify the region parameter. Otherwise, an error is reported. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # Use the bucket object for subsequent operations.
Use an OIDCRoleARN
After you set a worker node RAM role in Container Service for Kubernetes, applications in pods on the corresponding node can obtain the STS token of the associated role through the global meta service. This process is similar to how applications deployed on ECS obtain tokens. However, you may not want untrusted applications to obtain the STS token of the instance RAM role. Examples of untrusted applications include those deployed on the container cluster that are submitted by your customers and have code that is not open to you. To allow these untrusted applications to securely obtain the required STS tokens and achieve application-level permission minimization without affecting the security of your cloud resources, you can use the RAM Roles for Service Account (RRSA) feature. The underlying implementation of this method is an STS token. An Alibaba Cloud container cluster creates and mounts the corresponding service account OpenID Connect (OIDC) token files for different application pods and injects the relevant configuration information into environment variables. The Credentials tool obtains the configuration information from the environment variables and calls the AssumeRoleWithOIDC operation of STS to exchange the OIDC token for the STS token of the attached role. This method does not require you to provide an AccessKey pair or an STS token. This eliminates the risks of manual maintenance. For more information, see Use RRSA to configure RAM permissions for a ServiceAccount to achieve pod permission fencing.
You can add the alibabacloud_credentials dependency.
pip install alibabacloud_credentials
You can configure an OIDCRoleArn as the access credential.
# -*- coding: utf-8 -*- import oss2 from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config from oss2 import CredentialsProvider from oss2.credentials import Credentials import os class CredentialProviderWrapper(CredentialsProvider): def __init__(self, client): self.client = client def get_credentials(self): credential = self.client.get_credential() access_key_id = credential.access_key_id access_key_secret = credential.access_key_secret security_token = credential.security_token return Credentials(access_key_id, access_key_secret, security_token) config = Config( # Specify the credential type. Set the value to oidc_role_arn. type='oidc_role_arn', # The ARN of the RAM role. You can set RoleArn using the ALIBABA_CLOUD_ROLE_ARN environment variable. role_arn=os.environ.get('<RoleArn>'), # The ARN of the OIDC provider. You can set OidcProviderArn using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable. oidc_provider_arn=os.environ.get('<OidcProviderArn>'), # The path of the OIDC token file. You can set OidcTokenFilePath using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable. oidc_token_file_path=os.environ.get('<OidcTokenFilePath>'), # The name of the role session. You can set RoleSessionName using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. role_session_name='<RoleSessionName>', # Set a smaller permission policy. This parameter is optional. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"} policy='<Policy>', # Set the session expiration time. role_session_expiration=3600 ) cred = Client(config) credentials_provider = CredentialProviderWrapper(cred) # Note that ProviderAuthV4 indicates that Signature V4 is used. auth = oss2.ProviderAuthV4(credentials_provider) # 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 the endpoint to https://oss-cn-hangzhou.aliyuncs.com. endpoint = 'https://oss-cn-hangzhou.aliyuncs.com' # Set yourBucketName to the name of the bucket. bucket_name = 'yourBucketName' # Set the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. region = 'cn-hangzhou' # Initialize the bucket using the Auth instance. Note that when you use Signature V4, you must specify the region parameter. Otherwise, an error is reported. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # Use the bucket object for subsequent operations.
Use Credentials in the context of Function Compute
If your application's function is deployed and runs in Function Compute, you can use Credentials in the Function Compute context to initialize the credential provider. The underlying implementation of this method is an STS token. Function Compute obtains an STS token by assuming a server role based on the role configured for the function. It then passes the STS token to your application through the Credentials parameter in the context. The STS token is valid for 36 hours and cannot be modified. The maximum running time of a function is 24 hours. Therefore, the STS token does not expire during function execution, and you do not need to consider refreshing it. This method does not require you to provide an AccessKey pair or an STS token. This eliminates the risks of manual maintenance. For information about how to grant Function Compute access permissions to OSS, see Use a function role to grant Function Compute permissions to access other Alibaba Cloud services.
You can initialize the credential provider using Credentials in the Function Compute context.
# -*- coding: utf-8 -*- import oss2 from oss2 import CredentialsProvider from oss2.credentials import Credentials def handler(event, context): class CredentialProviderWrapper(CredentialsProvider): def get_credentials(self): creds = context.credentials return Credentials(creds.access_key_id, creds.access_key_secret, creds.security_token) credentials_provider = CredentialProviderWrapper() # Note that ProviderAuthV4 indicates that Signature V4 is used. auth = oss2.ProviderAuthV4(credentials_provider) # 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 the endpoint to https://oss-cn-hangzhou.aliyuncs.com. endpoint = 'https://oss-cn-hangzhou.aliyuncs.com' # Set yourBucketName to the name of the bucket. bucket_name = 'yourBucketName' # Set the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. region = 'cn-hangzhou' # Initialize the bucket using the Auth instance. Note that when you use Signature V4, you must specify the region parameter. Otherwise, an error is reported. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # Use the bucket object for subsequent operations. return 'success'
Use a CredentialsURI
If your application needs to obtain Alibaba Cloud credentials from an external system for flexible credential management and keyless access, you can use a CredentialsURI to initialize the credential provider. The underlying implementation of this method is an STS token. The Credentials tool obtains an STS token from the URI that you provide to complete the credential client initialization. This method does not require you to provide an AccessKey pair or an STS token. This eliminates the risks of manual maintenance.
A CredentialsURI is the server address from which an STS token is obtained.
The backend service that provides the CredentialsURI response must implement the logic for automatically refreshing the STS token. This ensures that your application can always obtain a valid credential.
To ensure that the Credentials tool correctly parses and uses the STS token, the URI response must follow this protocol:
Response status code: 200
Response body structure:
{ "Code": "Success", "AccessKeySecret": "AccessKeySecret", "AccessKeyId": "AccessKeyId", "Expiration": "2021-09-26T03:46:38Z", "SecurityToken": "SecurityToken" }
You can add the alibabacloud_credentials dependency.
pip install alibabacloud_credentials
You can configure a URI credential as the access credential.
# -*- coding: utf-8 -*- import oss2 from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config from oss2 import CredentialsProvider from oss2.credentials import Credentials class CredentialProviderWrapper(CredentialsProvider): def __init__(self, client): self.client = client def get_credentials(self): credential = self.client.get_credential() access_key_id = credential.access_key_id access_key_secret = credential.access_key_secret security_token = credential.security_token return Credentials(access_key_id, access_key_secret, security_token) config = Config( type='credentials_uri', # The URI of the credential, in the format of http://local_or_remote_uri/. You can set CredentialsUri using the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. credentials_uri='<CredentialsUri>', ) cred = Client(config) credentials_provider = CredentialProviderWrapper(cred) # Note that ProviderAuthV4 indicates that Signature V4 is used. auth = oss2.ProviderAuthV4(credentials_provider) # 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 the endpoint to https://oss-cn-hangzhou.aliyuncs.com. endpoint = 'https://oss-cn-hangzhou.aliyuncs.com' # Set yourBucketName to the name of the bucket. bucket_name = 'yourBucketName' # Set the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. region = 'cn-hangzhou' # Initialize the bucket using the Auth instance. Note that when you use Signature V4, you must specify the region parameter. Otherwise, an error is reported. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # Use the bucket object for subsequent operations.
Use an AccessKey pair that automatically rotates
If your application requires long-term access to OSS but is deployed in an environment where the AccessKey pair is at risk of being leaked and requires frequent manual rotation, you can use a ClientKey to initialize the credential provider. The underlying implementation of this method is an AccessKey pair. After you use a ClientKey, Key Management Service (KMS) can automatically and regularly rotate the managed RAM user's AccessKey pair. This makes the static RAM user AccessKey pair dynamic and reduces the risk of AccessKey pair leakage. In addition to regular rotation, KMS also supports immediate rotation to quickly replace a leaked AccessKey pair. This method eliminates the need to manually maintain an AccessKey pair, which reduces security risks and maintenance complexity. For information about how to obtain a ClientKey, see Create an application access point.
You can add the credential client dependency.
pip install aliyun-secret-manager-client
You can create a configuration file named
secretsmanager.properties
.# The type of the access credential. Set the value to client_key. credentials_type=client_key # Read the decryption password of the Client Key: Reading from an environment variable or a file is supported. Set only one. client_key_password_from_env_variable=<your client key private key password environment variable name> client_key_password_from_file_path=<your client key private key password file path> # The path of the private key file of the Client Key. client_key_private_key_path=<your client key private key file path> # The associated KMS service region. cache_client_region_id=[{"regionId":"<regionId>"}]
You can pass credential information using the configuration file.
# -*- coding: utf-8 -*- import json import oss2 from oss2 import CredentialsProvider from oss2.credentials import Credentials from alibaba_cloud_secretsmanager_client.secret_manager_cache_client_builder import SecretManagerCacheClientBuilder class CredentialProviderWrapper(CredentialsProvider): def get_credentials(self): secret_cache_client = SecretManagerCacheClientBuilder.new_client() secret_info = secret_cache_client.get_secret_info("<secretName>") secret_value_json = json.loads(secret_info.secret_value) return Credentials(secret_value_json["AccessKeyId"], secret_value_json["AccessKeySecret"]) credentials_provider = CredentialProviderWrapper() # Note that ProviderAuthV4 indicates that Signature V4 is used. auth = oss2.ProviderAuthV4(credentials_provider) # 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 the endpoint to https://oss-cn-hangzhou.aliyuncs.com. endpoint = 'https://oss-cn-hangzhou.aliyuncs.com' # Set yourBucketName to the name of the bucket. bucket_name = 'yourBucketName' # Set the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. region = 'cn-hangzhou' # Initialize the bucket using the Auth instance. Note that when you use Signature V4, you must specify the region parameter. Otherwise, an error is reported. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # Use the bucket object for subsequent operations.
Use custom access credentials
If none of the preceding credential configuration methods meet your requirements, you can customize the credential provisioning method by implementing the Credential Providers interface. Note that if the underlying implementation is an STS token, you must provide support for credential updates.
# -*- coding: utf-8 -*-
import oss2
from oss2 import CredentialsProvider
from oss2.credentials import Credentials
class CredentialProviderWrapper(CredentialsProvider):
def get_credentials(self):
# TODO
# Customize the method for obtaining access credentials.
# Return long-term credentials: access_key_id, access_key_secrect
return Credentials('<access_key_id>', '<access_key_secrect>')
# Return temporary credentials: access_key_id, access_key_secrect, token
# For temporary credentials, you need to refresh them based on their expiration time.
# return Credentials('<access_key_id>', '<access_key_secrect>', '<token>');
credentials_provider = CredentialProviderWrapper()
# Note that ProviderAuthV4 indicates that Signature V4 is used.
auth = oss2.ProviderAuthV4(credentials_provider)
# 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 the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# Set yourBucketName to the name of the bucket.
bucket_name = 'yourBucketName'
# Set the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
region = 'cn-hangzhou'
# Initialize the bucket using the Auth instance. Note that when you use Signature V4, you must specify the region parameter. Otherwise, an error is reported.
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
# Use the bucket object for subsequent operations.