All Products
Search
Document Center

:Configure access credentials for OSS SDK for Python

Last Updated:Mar 13, 2025

To use Object Storage Service (OSS) SDK for Python to initiate a request, you must configure access credentials, which are used to verify your identity and access permissions. You can select different types of access credentials based on the requirements for authentication and authorization.

Usage notes

  • For a list of OSS regions and endpoints, see Regions and endpoints.

  • For information about how to create an AccessKey pair for a RAM user, see Create an AccessKey pair for a RAM user.

  • Before you configure access credentials, make sure that the latest version of OSS SDK for Python is installed. For more information, see Installation.

  • Make sure that the alibabacloud-credentials version is 0.3.5 or later. An earlier version will cause errors.

Credential provider initialization

OSS supports multiple methods to initialize a credential provider. You can select a suitable method based on your actual authentication and authorization requirements.

Initialization method

Scenario

AccessKey pair or STS token required

Underlying credential

Credential validity period

Credential rotation or refresh method

Use the AccessKey pair of a RAM user

Applications are deployed and run in a secure and stable environment that is not vulnerable to external attacks, and need long-term access to cloud services without frequent credential rotation.

Yes

AccessKey pair

Long-term

Manual rotation

Use temporary access credentials provided by STS

Applications are deployed and run in an untrusted environment, in which case you want to manage the credential validity and the resources that can be accessed.

Yes

Security Token Service (STS) token

Temporary

Manual refresh

Use the ARN of a RAM role

Applications require access to cloud services, such as cross-account access.

Yes

STS token

Temporary

Automatic refresh

Use the RAM role of an ECS instance

Applications are deployed and run on Elastic Compute Service (ECS) instances, Elastic Container Instance, or Container Service for Kubernetes (ACK) worker nodes.

No

STS token

Temporary

Automatic refresh

Use the role of an OIDC IdP

Untrusted applications are deployed and run on ACK worker nodes.

No

STS token

Temporary

Automatic refresh

Use the Credentials parameter in the context of Function Compute

Functions of your applications are deployed and run in Function Compute.

No

STS token

Temporary

No need to refresh

Use the CredentialsURI

Applications require access credentials from external systems.

No

STS token

Temporary

Automatic refresh

Use an AccessKey pair that automatically rotates

Applications are deployed in an environment where AccessKey pairs are at high risk of leakage, and require frequent rotation of access credentials to gain long-term access to cloud services.

No

AccessKey pair

Long-term

Automatic rotation

Use custom access credentials

If none of the preceding methods meet your requirements, you can use a custom method to obtain access credentials.

Custom

Custom

Custom

Custom

Configuration examples for common scenarios

Use the AccessKey pair of a RAM user

Assume that your application requires long-term access to OSS without frequently rotating access credentials and runs in a secure and stable environment that is not vulnerable to external attacks. In this case, you can use an AccessKey pair (an AccessKey ID and an AccessKey secret) of your Alibaba Cloud account or a RAM user to initialize a credential provider. Take note that this method requires you to manually maintain an AccessKey pair. This poses security risks and increases maintenance complexity.

Warning
  • An Alibaba Cloud account has full permissions on its resources, and leaks of its AccessKey pair pose significant security risks. Therefore, we recommend that you use the AccessKey pair of a RAM user with the minimum required permissions to initialize a credential provider.

  • For information about how to create an AccessKey pair for a RAM user, see Create an AccessKey pair for a RAM user. The AccessKey pair of a RAM user is displayed only when the RAM user is created. Save the AccessKey pair in a timely manner. If you forget the AccessKey pair, create a new AccessKey pair for rotation.

Environment variables

  1. Configure environment variables for the AccessKey pair of the RAM user.

    Linux
    1. Run the following commands on the CLI to add the configurations of the environment variables 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
    2. Run the following command to apply the changes:

      source ~/.bashrc
    3. Run the following commands to check whether the environment variables take effect:

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET
    macOS
    1. Run the following command in the terminal to view the default shell type:

      echo $SHELL
    2. Configure environment variables based on the default shell type.

      Zsh
      1. Run the following commands to add the configurations of the environment variables 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
      2. Run the following command to apply the changes:

        source ~/.zshrc
      3. Run the following commands to check whether the environment variables take effect:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET
      Bash
      1. Run the following commands to add the configurations of the environment variables 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
      2. Run the following command to apply the changes:

        source ~/.bash_profile
      3. Run the following commands to check whether the environment variables take effect:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET
    Windows
    CMD
    1. Run the following commands in CMD:

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
    2. Run the following commands to check whether the environment variables take effect:

      echo %OSS_ACCESS_KEY_ID%
      echo %OSS_ACCESS_KEY_SECRET%
    PowerShell
    1. 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)
    2. Run the following commands to check whether the environment variable takes effect:

      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)

  2. To make sure that your settings are loaded, restart or refresh your compilation and runtime environments, such as the IDE, command-line tool, desktop applications, and services in the background.

  3. Pass credentials by using environment variables.

    # -*- coding: utf-8 -*-
    import oss2
    from oss2.credentials import 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. 
    endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
    
    # Specify the name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # Specify 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'
    
    # Use the AccessKey pair of the RAM user obtained from the environment variables to configure access credentials. Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
    # Use the bucket object for subsequent operations.

Static credentials

The following example shows how to hardcode access credentials of a RAM user in code:

Warning

Do not embed access credentials in application code deployed in a production environment. This method is intended only for testing.

# -*- 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 name of the bucket. 
bucket_name = 'yourBucketName'

# Specify 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 = 'LTAI5tQQx1DWEYK7********'
access_key_secret = 's5LkMqKmmKbt3zjs7MNJTj********'

# Use the AccessKey pair of the RAM user as access credentials. Note that AuthV4 indicates that the signature algorithm V4 is used. 
auth = oss2.AuthV4(access_key_id, access_key_secret)

# Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)

# Use the bucket object for subsequent operations.

Use temporary access credentials provided by STS

If your application needs to access OSS temporarily, you can use temporary access credentials provided by STS, which consist of an AccessKey pair and an STS token. Take note that this method requires you to manually maintain an STS token. This poses security risks and increases maintenance complexity. If you want to prolong access after the existing STS token expires, you need to manually refresh the STS token.

Important
  • You can obtain temporary access credentials by calling the AssumeRole API operation. For more information, see AssumeRole.

  • You can also obtain temporary access credentials by using the SDK. For more information, see Use temporary access credentials provided by STS to access OSS.

  • You must specify a validity period for the STS token when you generate the token. An expired STS token cannot be used.

  • For a list of STS endpoints, see Endpoints.

Environment variables

  1. Configure environment variables for temporary access credentials.

    Mac OS X/Linux/Unix

    Warning
    • Note that the temporary access credentials (AccessKey ID, AccessKey secret, and STS token) provided by STS are used instead of the AccessKey ID and AccessKey secret of the RAM user.

    • The AccessKey ID provided by STS starts with STS. Example: STS.L4aBSCSJVMuKg5U1****.

    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

    Warning
    • Note that the temporary access credentials (AccessKey ID, AccessKey secret, and STS token) provided by STS are used instead of the AccessKey pair (AccessKey ID and AccessKey secret) of the RAM user.

    • The AccessKey ID provided by STS starts with STS. Example: STS.L4aBSCSJVMuKg5U1****.

    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>
  2. Pass credential information by using environment variables.

    # -*- coding: utf-8 -*-
    import oss2
    from oss2.credentials import 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. 
    endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
    
    # Specify the name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # Specify 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'
    
    # Use the AccessKey ID, AccessKey secret, and STS token as access credentials. ProviderAuthV4 indicates that the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
    # Use the bucket object for subsequent operations.

Static credentials

The following example shows how to hardcode temporary access credentials in code:

Warning

Do not embed access credentials in application code deployed in a production environment. This method is intended only for testing.

# -*- coding: utf-8 -*-
import oss2

# Specify the temporary AccessKey ID and AccessKey secret provided by STS, instead of the AccessKey ID and AccessKey secret of an Alibaba Cloud account. 
# Note that an AccessKey ID provided by STS starts with STS. 
sts_access_key_id = 'STS.NTvKBumxJdJbN3U2********'
sts_access_key_secret = '6dg5r6N56FJ75JQMErowXVZYAnSGHXFHJwcN********'
# Specify the STS token obtained from STS. 
security_token = '********'

# 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 name of the bucket. 
bucket_name = 'yourBucketName'

# Specify 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, indicating that the signature algorithm V4 is used. 
auth = oss2.StsAuth(sts_access_key_id,
                    sts_access_key_secret,
                    security_token,
                    auth_version="v4")

# Use the StsAuth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)

# Use the bucket object for subsequent operations.

Configuration examples for other scenarios

Use the ARN of a RAM role

If you need to authorize your application to access OSS, for example, in a cross-account access scenario, you can use the Alibaba Cloud Resource Name (ARN) of a RAM role to initialize a credential provider. The underlying logic of this method is to use an STS token obtained from STS to configure access credentials. The Credentials tool obtains an STS token based on the ARN of the RAM role and refreshes the STS token by calling the AssumeRole operation before the session expires. You can specify a policy to limit the permissions granted to the RAM role.

Important
  • An Alibaba Cloud account has full permissions on its resources, and leaks of its AccessKey pair pose significant security risks. Therefore, we recommend that you use the AccessKey pair of a RAM user with the minimum required permissions to initialize a credential provider.

  • For information about how to create an AccessKey pair for a RAM user, see Create an AccessKey pair for a RAM user. The AccessKey pair of a RAM user is displayed only when the RAM user is created. Save the AccessKey pair in a timely manner. If you forget the AccessKey pair, create a new AccessKey pair for rotation.

  • You can create a RAM role by calling the CreateRole operation. The ARN of the RAM role is included in the response. For more information, see CreateRole.

  1. Add the alibabacloud_credentials dependency.

    pip install alibabacloud_credentials
  2. 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',
        # Specify the ARN of the RAM role that you want your application to assume by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole
        role_arn='<RoleArn>',
        # Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
        role_session_name='<RoleSessionName>',
        # (Optional) Specify limited permissions. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
        policy='<Policy>',
        # (Optional) Specify the validity period of the role session.
        role_session_expiration=3600
    )
    
    cred = Client(config)
    
    credentials_provider = CredentialProviderWrapper(cred)
    
    # Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(credentials_provider)
    
    # 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 name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # Specify 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'
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
    # Use the bucket object for subsequent operations.
    

Use the RAM role of an ECS instance

If your application runs on an ECS instance, an elastic container instance, or an ACK worker node, we recommend that you use the RAM role of the ECS instance to initialize a credential provider. The underlying logic of this method is to use an STS token obtained from STS to configure access credentials. You can attach a RAM role to an ECS instance, an elastic container instance, or an ACK worker node to automatically refresh the STS token on the instance. This method does not require an AccessKey pair or STS token, eliminating the risks associated with manually managing these credentials. You can create a RAM role by calling the CreateRole operation. The ARN is included in the response. For more information, see CreateRole.

  1. Add the alibabacloud_credentials dependency.

    pip install alibabacloud_credentials
  2. Use the RAM role to provide 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
    
    
    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',      # Specify the credential type. Set the value to ecs_ram_role. 
        role_name='<RoleName>'    # Specify the name of the RAM role that is attached to the ECS instance. The RAM role name is optional. If you do not configure this parameter, the system automatically searches for a RAM role. We recommend that you configure this parameter to reduce the number of requests. 
    )
    
    
    cred = Client(config)
    
    credentials_provider = CredentialProviderWrapper(cred)
    
    # Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(credentials_provider)
    
    # 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 name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # Specify 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'
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
    # Use the bucket object for subsequent operations.
    

Use the role of an OIDC IdP

After the RAM role is configured on the ACK worker node, applications within pods on that node can retrieve the STS token for the attached role by using the metadata server, similar to an application deployed on an ECS instance. However, you might not want untrusted applications, such as those submitted by customers without disclosing the application code to you, to access the metadata server for obtaining the STS token of the RAM role attached to the worker node. To ensure the security of cloud resources, allow untrusted applications to securely obtain the required STS token, and minimize application-level permissions, you can use the RAM Roles for Service Account (RRSA) feature. The underlying logic of this method is to use an STS token obtained from STS to configure access credentials. ACK creates and mounts corresponding OpenID Connect (OIDC) token files for different application pods, and passes relevant configuration information to environment variables. The Credentials tool obtains the configuration information from the environment variables and calls the AssumeRoleWithOIDC operation of STS to obtain the STS token for attached roles. This method does not require an AccessKey pair or STS token, eliminating the risks associated with manually managing these credentials. For more information, see Use RRSA to authorize different pods to access different cloud services.

  1. Add the alibabacloud_credentials dependency.

    pip install alibabacloud_credentials
  1. Use the role ARN of the OIDC IdP 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(
        # Set the credential type to oidc_role_arn. 
        type='oidc_role_arn',
        # Specify the ARN of the RAM role by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable.
        role_arn=os.environ.get('<RoleArn>'),
        # Specify the ARN of the OIDC IdP by specifying the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
        oidc_provider_arn=os.environ.get('<OidcProviderArn>'),
        # Specify the path of the OIDC token file by specifying the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
        oidc_token_file_path=os.environ.get('<OidcTokenFilePath>'),
        # Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
        role_session_name='<RoleSessionName>',
        # (Optional) Specify limited permissions. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
        policy='<Policy>',
        # Specify the validity period of the session.
        role_session_expiration=3600
    )
    
    
    cred = Client(config)
    
    credentials_provider = CredentialProviderWrapper(cred)
    
    # Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(credentials_provider)
    
    # 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 name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # Specify 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'
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    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 the function for your application is deployed and run in Function Compute, you can initialize the credential provider by using Credentials in the context of Function Compute context. The underlying logic of this method is to use an STS token obtained from STS to configure access credentials. Function Compute obtains an STS token by assuming a service role based on the role configured for the function. Then, the STS token is passed to your application by using Credentials in the context. The STS token is valid for 36 hours. You cannot change its validity period. A function can execute for up to 24 hours. You do not need to refresh the STS token during function execution, because it remains valid throughout the execution of the function. This method does not require an AccessKey pair or STS token, eliminating the risks associated with manually managing these credentials. For more information about how to authorize Function Compute to access OSS, see Grant Function Compute permissions to access other Alibaba Cloud services.

  1. Initializes the credential provider by 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 the signature algorithm V4 is used. 
        auth = oss2.ProviderAuthV4(credentials_provider)
    
        # 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 name of the bucket. 
        bucket_name = 'yourBucketName'
    
        # Specify 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'
    
        # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
        bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
        # Use the bucket object for subsequent operations.
    
        return 'success'
    

Use the CredentialsURI

If your application needs to obtain Alibaba Cloud credentials from an external system to implement flexible credential management and keyless access, you can use the CredentialsURI to initialize a credential provider. The underlying logic of this method is to use an STS token obtained from STS to configure access credentials. The Credentials tool obtains the STS token by using the specified URI to initialize the client. This method does not require an AccessKey pair or STS token, eliminating the risks associated with manually managing these credentials.

Important
  • The CredentialsURI refers to the address of the server that generates an STS token.

  • The backend service that provides the credentials URI response must automatically refresh the STS token to ensure that your application can always obtain valid credentials.

  1. To allow the Credentials tool to correctly parse and use an STS token, the URI must comply with the following requirements:

    • Response status code: 200

    • Response body structure:

      {
          "Code": "Success",
          "AccessKeySecret": "AccessKeySecret",
          "AccessKeyId": "AccessKeyId",
          "Expiration": "2021-09-26T03:46:38Z",
          "SecurityToken": "SecurityToken"
      }
  2. Add the alibabacloud_credentials dependency.

    pip install alibabacloud_credentials
  3. Configure the URI 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',
        # Specify the URI of the credential in the http://local_or_remote_uri/ format by specifying the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
        credentials_uri='<CredentialsUri>',
    )
    
    
    cred = Client(config)
    
    credentials_provider = CredentialProviderWrapper(cred)
    
    # Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(credentials_provider)
    
    # 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 name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # Specify 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'
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    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 needs long-term access to OSS, you need to manually rotate the AccessKey pair to reduce credential leak risks. In this case, you can use a client key to initialize the credential provider. The underlying logic of this method is to use an AccessKey pair to access OSS resources. After you use a client key, Key Management Service (KMS) can automatically and regularly rotate the AccessKey pair of a managed RAM user and dynamically change the static AccessKey pair of the RAM user. This reduces the risk of AccessKey pair leaks. KMS also supports immediate rotation to quickly disable a leaked AccessKey pair. This eliminates the need to manually maintain an AccessKey pair and reduces security risks and maintenance complexity. For more information about how to obtain a client key, see Create an AAP.

  1. Add credential dependencies.

    pip install aliyun-secret-manager-client
  2. Create a configuration file named secretsmanager.properties.

    # Set the credential type to client_key.
    credentials_type=client_key
    
    # Specify the decryption password of the client key. You can read the decryption password from environment variables or a file.
    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>
    
    # Specify the path of the private key file of the client key.
    client_key_private_key_path=<your client key private key file path>
    
    # Specify the ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"<regionId>"}]
  3. Pass credentials by 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 the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(credentials_provider)
    
    # 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 name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # Specify 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'
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    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 methods meet your requirements, you can specify a custom method to obtain access credentials by calling the CredentialsProvider operation. Take note that if the underlying implementation is based on an STS token, you need to provide credential update support.

# -*- coding: utf-8 -*-
import oss2
from oss2 import CredentialsProvider
from oss2.credentials import Credentials


class CredentialProviderWrapper(CredentialsProvider):
    def get_credentials(self):
        # TODO
        # Specify the method used to obtain the custom access credentials.

        # Return long-term access credentials (an AccessKey ID and an AccessKey secret).
        return Credentials('<access_key_id>', '<access_key_secrect>')

        # Return temporary access credentials (an AccessKey ID, an AccessKey secret, and an STS token.
        # Refresh the temporary access credentials based on the validity period. 
        # return Credentials('<access_key_id>', '<access_key_secrect>', '<token>');


credentials_provider = CredentialProviderWrapper()

# Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
auth = oss2.ProviderAuthV4(credentials_provider)

# 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 name of the bucket. 
bucket_name = 'yourBucketName'

# Specify 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'

# Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)

# Use the bucket object for subsequent operations.

FAQ

How can I distinguish between temporary access credentials provided by STS and the AccessKey pair of a RAM user when I initialize a credential provider?

When you use temporary access credentials (AccessKey ID, AccessKey secret, and STS token) obtained from STS to initialize a credential provider, do not confuse the AccessKey ID returned by STS with the AccessKey ID of the RAM user. The AccessKey ID obtained from STS starts with STS. Example:

image

How do I view the AccessKey ID of a RAM user? Can I view the AccessKey secret of an AccessKey pair?

  1. You can view the AccessKey pair of a RAM user by following steps described in View the information about AccessKey pairs of a RAM user.

  2. The AccessKey secret of a RAM user is displayed only when the AccessKey pair is created. You cannot view the AccessKey pair at a later time. If you forget the AccessKey secret, you cannot retrieve the AccessKey secret. In this case, you can directly create a new AccessKey pair for rotation in the RAM console. For more information, see Create an AccessKey pair.

How do I fix an AccessDenied error that occurs when I use the AccessKey pair of a RAM user to upload files?

The AccessDenied error occurs typically for two reasons: wrong AccessKey pair or a lack of upload permissions. You can perform the following steps to troubleshoot the AccessDenied error:

  1. Check whether the provided AccessKey pair is correct by following the instructions described in View the information about AccessKey pairs of a RAM user.

  2. The AccessKey secret of a RAM user is displayed only when the AccessKey pair is created. You cannot view the AccessKey pair at a later time. If you forget the AccessKey secret, you cannot retrieve the AccessKey secret. In this case, you can directly create a new AccessKey pair for rotation in the RAM console. For more information, see Create an AccessKey pair.

  3. In the RAM console, check whether the RAM user has the permission to upload files to OSS. If not, grant the required permissions.

How do I fix a connection error when I access OSS by using a public OSS endpoint?

If you encounter a connection error when accessing OSS over the public endpoint, it may be due to an incorrect endpoint. To fix the error, perform the following checks:

  1. Check the region of the bucket in the OSS console.

  2. Check whether the specified endpoint is the correct one for the region. For example, if the bucket is located in the China(Hangzhou) region, use the oss-cn-hangzhou.aliyuncs.com endpoint to enable public network access. For a list of OSS endpoints, see Regions and endpoints.

  3. Check whether your environment can connect to the Internet.

If an error is reported, how do I determine the type of the error?

OSS provides error codes to help you determine the specific type of an error. For example, you can see 02-AUTH for common authentication errors.