All Products
Search
Document Center

Alibaba Cloud SDK:Manage access credentials

Last Updated:Apr 03, 2025

When you call API operations to manage cloud resources by using Alibaba Cloud SDKs, you must configure valid credential information. The Credentials tool of Alibaba Cloud provides a set of easy-to-use features and supports various types of credentials, including the default credential, AccessKey pairs, and Security Token Service (STS) tokens. The Credentials tool helps you obtain and manage credentials. This topic describes the order based on which the Credentials tool obtains the default credential. You can develop a thorough knowledge of configuring and managing credentials in Alibaba Cloud SDKs. This ensures that you can perform operations on cloud resources in an efficient and secure manner.

Background information

A credential is a set of information that is used to prove the identity of a user. When you log on to the system, you must use a valid credential to complete identity authentication. The following types of credentials are commonly used:

  1. The AccessKey pair of an Alibaba Cloud account or a Resource Access Management (RAM) user. An AccessKey pair is permanently valid and consists of an AccessKey ID and an AccessKey secret.

  2. An STS token of a RAM role. An STS token is a temporary credential. You can specify a validity period and access permissions for an STS token. For more information, see What is STS?

  3. A bearer token. It is used for identity authentication and authorization.

Prerequisites

  • Python 3.7 or later is installed.

  • Alibaba Cloud SDK V2.0 is installed.

Install the Credentials tool

We recommend that you use pip to install Alibaba Cloud Credentials for Python. Make sure that pip is installed. For more information, see pip documentation.

pip install alibabacloud_credentials
  1. We recommend that you use the latest version of Alibaba Cloud Credentials for Python. This ensures that all credentials are supported.

  2. For information about all released versions of Alibaba Cloud Credentials for Python, see ChangeLog.md.

Initialize a Credentials client

You can use one of the following methods to initialize a Credentials client based on your business requirements:

Important

If you use a plaintext AccessKey pair in a project, the AccessKey pair may be leaked due to improper permission management on the code repository. This may threaten the security of all resources within the account to which the AccessKey pair belongs. We recommend that you store the AccessKey pair in environment variables or configuration files.

Method 1: Use the default credential provider chain

If you do not specify a method to initialize a Credentials client, the default credential provider chain is used. For more information, see Default credential provider chain.

from alibabacloud_credentials.client import Client as CredClient
from alibabacloud_tea_openapi.models import Config

# Do not specify a method to initialize a Credentials client.
credentialsClient = CredClient()
config = Config(credential=credentialsClient)

Example

You can use the default credential provider chain to automatically create access credentials and call the API operations of Alibaba Cloud services without the need to use a hard-coded AccessKey pair.

The following sample code provides an example on how to call the DescribeRegions operation of Elastic Compute Service (ECS). Before you call this operation, you must install ECS SDK for Python.

# Import a Credentials client and create an alias for the client. 
from alibabacloud_credentials.client import Client as CredClient
# Import an ECS SDK client and create an alias for the client. 
from alibabacloud_ecs20140526.client import Client as EcsClient
# Initiate a request to call the DescribeRegions operation of ECS. 
from alibabacloud_ecs20140526.models import DescribeRegionsRequest
# Import the core Alibaba Cloud SDK package. 
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions

# Use the default credential to initialize the Credentials client. 
credentialsClient = CredClient()
ecsConfig = Config(credential=credentialsClient)
# Specify the endpoint of ECS. 
ecsConfig.endpoint = 'ecs.cn-hangzhou.aliyuncs.com'
# Use the Credentials client to initialize the ECS SDK client. 
ecsClient = EcsClient(ecsConfig)
# Initialize a request to call the DescribeRegions operation. 
request = DescribeRegionsRequest()
# Initialize the runtime configurations. 
runtime_options = RuntimeOptions()
# Call the DescribeRegions operation and obtain a response. 
response = ecsClient.describe_regions_with_options(request, runtime_options)
print(response.to_map())

Method 2: Use an AccessKey pair

You can create an AccessKey pair that is used to call API operations for your Alibaba Cloud account or a RAM user. For more information, see Create an AccessKey pair. Then, you can use the AccessKey pair to initialize a Credentials client.

Warning

An Alibaba Cloud account has full permissions on resources within the account. AccessKey pair leaks of an Alibaba Cloud account pose critical threats to the system.

Therefore, we recommend that you use an AccessKey pair of a RAM user that is granted permissions based on the principle of least privilege (PoLP) to initialize a Credentials client.

import os
from alibabacloud_credentials.client import Client
from alibabacloud_credentials.models import Config

config = Config(
	type='access_key',
	access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
	access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
)
cred = Client(config)

Example

You can use the Credentials tool to read an AccessKey pair and use the AccessKey pair as a credential to call the API operations of Alibaba Cloud services.

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for Python.

import os

# Import a Credentials client and create an alias for the client. 
from alibabacloud_credentials.client import Client as CredClient
from alibabacloud_credentials.models import Config as CreConfig
# Import an ECS SDK client and create an alias for the client. 
from alibabacloud_ecs20140526.client import Client as EcsClient
# Initiate a request to call the DescribeRegions operation of ECS. 
from alibabacloud_ecs20140526.models import DescribeRegionsRequest
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions

# Use an AccessKey pair to initialize the Credentials client. 
credentialsConfig = CreConfig(
    # Specify the credential type. 
    type='access_key',
    # Specify the AccessKey ID. 
    access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    # Specify the AccessKey secret. 
    access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
)
credentialClient = CredClient(credentialsConfig)

ecsConfig = Config(credential=credentialClient)
# Specify the endpoint of ECS. 
ecsConfig.endpoint = 'ecs.cn-hangzhou.aliyuncs.com'
# Initialize the ECS SDK client. 
ecsClient = EcsClient(ecsConfig)

# Initialize a request to call the DescribeRegions operation. 
request = DescribeRegionsRequest()
# Initialize the runtime configurations. 
runtime_options = RuntimeOptions()
# Call the DescribeRegions operation and obtain a response. 
response = ecsClient.describe_regions_with_options(request, runtime_options)
print(response.to_map())

Method 3: Use an STS token

You can call the AssumeRole operation of STS as a RAM user to obtain an STS token. You can specify the maximum validity period of the STS token. The following example shows how to initialize a Credentials client by using an STS token. The example does not show how to obtain an STS token.

import os

from alibabacloud_credentials.client import Client
from alibabacloud_credentials.models import Config

config = Config(
    type='sts',
    # Obtain the AccessKey ID from the environment variable.
    access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    # Obtain the AccessKey secret from the environment variable.
    access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    # Obtain the temporary STS token from the environment variable.
    security_token=os.environ.get('ALIBABA_CLOUD_SECURITY_TOKEN')
)
credClient = Client(config)

Example

You can use the Credentials tool to read an STS token and use the STS token as a credential to call the API operations of Alibaba Cloud services.

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for Python and STS SDK for Python.

import os

from alibabacloud_credentials.client import Client as CredClient
from alibabacloud_credentials.models import Config as CreConfig
from alibabacloud_ecs20140526.client import Client as EcsClient
from alibabacloud_ecs20140526.models import DescribeRegionsRequest
from alibabacloud_sts20150401.client import Client as Sts20150401Client
from alibabacloud_sts20150401.models import AssumeRoleRequest
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions

# Obtain the AccessKey pair of a RAM user from the environment variables.
config = Config(
    access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
    access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
config.endpoint = "sts.aliyuncs.com"
stsClient = Sts20150401Client(config)

# Specify the request parameters for calling the AssumeRole operation.
assume_role_request = AssumeRoleRequest(
    // Specify the validity period of the session.
    duration_seconds=3600,
    # Specify the Alibaba Cloud Resource Name (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='<role_arn>',
    # Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
    role_session_name='<role_session_name>'
)
runtime = RuntimeOptions()
try:
    resp = stsClient.assume_role_with_options(assume_role_request, runtime)
    assumeRoleResponseBodyCredentials = resp.body.credentials

    # Use an STS token to initialize the Credentials client. 
    credentialsConfig = CreConfig(
        # Specify the credential type. 
        type='sts',
        # Specify the AccessKey ID. 
        access_key_id=assumeRoleResponseBodyCredentials.access_key_id,
        # Specify the AccessKey secret. 
        access_key_secret=assumeRoleResponseBodyCredentials.access_key_secret,
        # Specify the STS token. 
        security_token=assumeRoleResponseBodyCredentials.security_token
    )
    credentialClient = CredClient(credentialsConfig)
    ecsConfig = Config(credential=credentialClient)
    # Specify the endpoint of ECS. 
    ecsConfig.endpoint = 'ecs.cn-hangzhou.aliyuncs.com'
    # Initialize the ECS SDK client. 
    ecsClient = EcsClient(ecsConfig)

    # Initialize a request to call the DescribeRegions operation. 
    request = DescribeRegionsRequest()
    # Initialize the runtime configurations. 
    runtime_options = RuntimeOptions()
    # Call the DescribeRegions operation and obtain a response. 
    response = ecsClient.describe_regions_with_options(request, runtime_options)
    print(response.to_map())
except Exception as error:
    # Report an error message.
    print(error.message)

Method 4: Use an AccessKey pair and a RAM role

The underlying logic of this method is to use an STS token to initialize a Credentials client. After you specify the ARN of a RAM role, the Credentials tool can obtain an STS token from STS. You can also use the policy parameter to limit the permissions of the RAM role.

import os

from alibabacloud_credentials.client import Client as CredClient
from alibabacloud_credentials.models import Config as CredConfig

credentialsConfig = CredConfig(
    access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    access_key_secret=os.environ.get('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='<role_arn>',
    # Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
    role_session_name='<role_session_name>',
    # Optional. Specify the minimum permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    policy='<policy>',
    role_session_expiration=3600
)
credentialsClient = CredClient(credentialsConfig)

Example

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for Python.

import os

from alibabacloud_credentials.client import Client as CredClient
from alibabacloud_credentials.models import Config as CredConfig
from alibabacloud_ecs20140526.client import Client as EcsClient
from alibabacloud_ecs20140526.models import DescribeRegionsRequest
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions

# Use an AccessKey pair and a RAM role to initialize the Credentials client. 
credentialsConfig = CredConfig(
    type='ram_role_arn',  # Specify the type of the credential. 
    access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),  # Obtain the AccessKey ID from the environment variable. 
    access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),  # Obtain the AccessKey secret from the environment variable. 
    # 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='<role_arn>',
    # Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
    role_session_name='<role_session_name>',
    # Optional. Specify the minimum permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    policy='<policy>',
    role_session_expiration=3600  # Specify the validity period of the session.
)
credentialsClient = CredClient(credentialsConfig)
ecsConfig = Config(credential=credentialsClient)
# Specify the endpoint of the cloud service. 
ecsConfig.endpoint = 'ecs.aliyuncs.com'
# Use the Credentials client to initialize the ECS SDK client. 
ecsClient = EcsClient(ecsConfig)
# Initialize a request to call the DescribeRegions operation. 
request = DescribeRegionsRequest()
# Initialize the runtime configurations. 
runtime_options = RuntimeOptions()
# Call the DescribeRegions operation and obtain a response. 
response = ecsClient.describe_regions_with_options(request, runtime_options)
print(response.to_map())

Method 5: Use the RAM role of an ECS instance

ECS instances and elastic container instances can be assigned RAM roles. Programs that run on the instances can use the Credentials tool to automatically obtain an STS token for the RAM role. The STS token can be used to initialize the Credentials client.

By default, the Credentials tool accesses the metadata server of ECS in security hardening mode (IMDSv2). If an exception is thrown, the Credentials tool switches to the normal mode (IMDSv1). You can also configure the enable_imds_v1 parameter or the ALIBABA_CLOUD_IMDSV1_DISABLE environment variable to specify the exception handling logic. Valid values:

  • false (default): The Credentials tool continues to obtain the access credential in normal mode (IMDSv1).

  • true: The exception is thrown and the Credentials tool continues to obtain the access credential in security hardening mode (IMDSv2).

The configurations for the metadata server determine whether the server supports the security hardening mode (IMDSv2).

In addition, you can specify ALIBABA_CLOUD_ECS_METADATA_DISABLED=true to disable access from the Credentials tool to the metadata server of ECS.

Note
  • For more information about ECS instance metadata, see Obtain instance metadata.

  • For more information about how to attach a RAM role to an ECS instance, see the "Create an instance RAM role and attach the instance RAM role to an ECS instance" section of the Instance RAM roles topic. For more information about how to attach a RAM role to an elastic container instance, see the "Assign the instance RAM role to an elastic container instance" section of the Use an instance RAM role by calling API operations topic.

Note

If you obtain an STS token in security hardening mode (IMDSv2), make sure that the version of alibabacloud_credentials is 0.3.6 or later.

from alibabacloud_credentials.client import Client as CredClient
from alibabacloud_credentials.models import Config as CredConfig

credentialsConfig = CredConfig(
	type='ecs_ram_role',
	# Optional. Specify the name of the RAM role of the ECS instance by specifying the ALIBABA_CLOUD_ECS_METADATA environment variable. If you do not specify this parameter, the value is automatically obtained. We recommend that you specify this parameter to reduce the number of requests.
	role_name='<role_name>',
	# Default value: False. This parameter is optional. True: The security hardening mode (IMDSv2) is forcibly used. False: The system preferentially attempts to obtain the access credential in security hardening mode (IMDSv2). If the attempt fails, the system switches to the normal mode (IMDSv1) to obtain access credentials.
	# enable_imds_v1=True,
)
credentialsClient = CredClient(credentialsConfig)

Example

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for Python.

# Import a Credentials client and create an alias for the client. 
from alibabacloud_credentials.client import Client as CredClient
from alibabacloud_credentials.models import Config as CredConfig
# Import an ECS SDK client and create an alias for the client. 
from alibabacloud_ecs20140526.client import Client as EcsClient
# Initiate a request to call the DescribeRegions operation of ECS. 
from alibabacloud_ecs20140526.models import DescribeRegionsRequest
# Import the core Alibaba Cloud SDK package. 
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions

# Use the RAM role of an ECS instance to initialize the Credentials client. 
credentialsConfig = CredConfig(
    type='ecs_ram_role',  # Specify the type of the credential. 
    # Optional. Specify the name of the RAM role of the ECS instance by specifying the ALIBABA_CLOUD_ECS_METADATA environment variable. If you do not specify this variable, the value is automatically obtained. We recommend that you specify this variable to reduce the number of requests.
    role_name='<role_name>'
)
credentialsClient = CredClient(credentialsConfig)
ecsConfig = Config(credential=credentialsClient)
# Specify the endpoint of the cloud service. 
ecsConfig.endpoint = 'ecs.aliyuncs.com'
# Use the Credentials client to initialize the ECS SDK client. 
ecsClient = EcsClient(ecsConfig)

# Initialize a request to call the DescribeRegions operation. 
request = DescribeRegionsRequest()
# Initialize the runtime configurations. 
runtime_options = RuntimeOptions()
# Call the DescribeRegions operation and obtain a response. 
response = ecsClient.describe_regions_with_options(request, runtime_options)
print(response.to_map())

Method 6: Use the RAM role of an OIDC IdP

Note

Make sure that the version of alibabacloud_credentials is 0.3.1 or later.

After you attach a RAM role to a worker node in an Container Service for Kubernetes, applications in the pods on the worker node can use the metadata server to obtain an STS token the same way in which applications on ECS instances do. However, if an untrusted application is deployed on the worker node, such as an application that is submitted by your customer and whose code is not available to you, you may not want the application to use the metadata server to obtain an STS token of the RAM role attached to the worker node. To ensure the security of cloud resources and enable untrusted applications to securely obtain required STS tokens, you can use the RAM Roles for Service Accounts (RRSA) feature to grant permissions to an application based on the PoLP. In this case, the ACK cluster creates a service account OpenID Connect (OIDC) token file, associates the token file with a pod, and then injects relevant environment variables into the pod. Then, the Credentials tool uses the environment variables to call the AssumeRoleWithOIDC operation of STS and obtains an STS token of the RAM role. For more information about the RRSA feature, see Use RRSA to authorize different pods to access different cloud services.

The following environment variables are injected into the pod:

ALIBABA_CLOUD_ROLE_ARN: the ARN of the RAM role.

ALIBABA_CLOUD_OIDC_PROVIDER_ARN: the ARN of the OIDC identity provider (IdP).

ALIBABA_CLOUD_OIDC_TOKEN_FILE: the path of the OIDC token file.

from alibabacloud_credentials.client import Client
from alibabacloud_credentials.models import Config

config = Config(
    type='oidc_role_arn',
    # Specify the ARN of the RAM role by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable.
    role_arn='<role_arn>',
    # Specify the ARN of the OIDC IdP by specifying the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
    oidc_provider_arn='<oidc_provider_arn>',
    # Specify the path of the OIDC token file by specifying the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
    oidc_token_file_path='<oidc_token_file_path>',
    # Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
    role_session_name='<role_session_name>',
    # Optional. Specify the minimum permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    policy='<policy>',
    # Specify the validity period of the session.
    role_session_expiration=3600
)
cred = Client(config)

access_key_id = cred.get_access_key_id()
access_key_secret = cred.get_access_key_secret()
security_token = cred.get_security_token()
cred_type = cred.get_type()

Example

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for Python.

from alibabacloud_credentials.client import Client as CredClient
from alibabacloud_credentials.models import Config as CredConfig
from alibabacloud_ecs20140526.client import Client as EcsClient
from alibabacloud_ecs20140526.models import DescribeRegionsRequest
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions

# Use the RAM role of an OIDC IdP to initialize the Credentials client. 
credentialsConfig = CredConfig(
    type='oidc_role_arn',
    # Specify the ARN of the RAM role by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable.
    role_arn='<role_arn>',
    # Specify the ARN of the OIDC IdP by specifying the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
    oidc_provider_arn='<oidc_provider_arn>',
    # Specify the path of the OIDC token file by specifying the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
    oidc_token_file_path='<oidc_token_file_path>',
    # Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
    role_session_name='<role_session_name>',
    # Optional. Specify the minimum permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    policy='<policy>',
    # Specify the validity period of the session.
    role_session_expiration=3600
)
credentialsClient = CredClient(credentialsConfig)
ecsConfig = Config(credential=credentialsClient)
# Specify the endpoint of the cloud service. 
ecsConfig.endpoint = 'ecs.aliyuncs.com'
# Use the Credentials client to initialize the ECS SDK client. 
ecsClient = EcsClient(ecsConfig)

# Initialize a request to call the DescribeRegions operation. 
request = DescribeRegionsRequest()
# Initialize the runtime configurations. 
runtime_options = RuntimeOptions()
# Call the DescribeRegions operation and obtain a response. 
response = ecsClient.describe_regions_with_options(request, runtime_options)
print(response.to_map())

Method 7: Use a credential URI

The underlying logic of this method is to use an STS token to initialize a Credentials client. The Credentials tool uses the uniform resource identifier (URI) that you provide to obtain an STS token. The STS token is then used to initialize a Credentials client.

from alibabacloud_credentials.client import Client
from alibabacloud_credentials.models import Config

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='<credentials_uri>',
)
cred = Client(config)

access_key_id = cred.get_access_key_id()
access_key_secret = cred.get_access_key_secret()
security_token = cred.get_security_token()
cred_type = cred.get_type()

Example

To call the API operations of Alibaba Cloud services, you can specify a local or remote URI for credentials and use the Credentials tool to obtain and automatically update an STS token based on the local or remote URI.

To call the API operations of an Alibaba Cloud service, you must install dependencies for the Alibaba Cloud service. The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for Python.

from alibabacloud_credentials.client import Client as CredClient
from alibabacloud_credentials.models import Config as CredConfig
from alibabacloud_ecs20140526.client import Client as EcsClient
from alibabacloud_ecs20140526.models import DescribeRegionsRequest
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions

# Use a URI to initialize the Credentials client. 
credentialsConfig = CredConfig(
    # Specify the credential type. 
    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='<credentials_uri>',
)
credentialsClient = CredClient(credentialsConfig)
ecsConfig = Config(credential=credentialsClient)
# Specify the endpoint of the cloud service. 
ecsConfig.endpoint = 'ecs.aliyuncs.com'
# Use the Credentials client to initialize the ECS SDK client. 
ecsClient = EcsClient(ecsConfig)

# Initialize a request to call the DescribeRegions operation. 
request = DescribeRegionsRequest()
# Initialize the runtime configurations. 
runtime_options = RuntimeOptions()
# Call the DescribeRegions operation and obtain a response. 
response = ecsClient.describe_regions_with_options(request, runtime_options)
print(response.to_map())

Method 8: Use a bearer token

Only Cloud Call Center allows you to use a bearer token to initialize a Credentials client.

from alibabacloud_credentials.client import Client
from alibabacloud_credentials.models import Config

config = Config(
	type='bearer',
	# Enter the bearer token.
	bearer_token='<BearerToken>',
)
cred = Client(config)

access_key_id = cred.get_access_key_id()
access_key_secret = cred.get_access_key_secret()
security_token = cred.get_security_token()
cred_type = cred.get_type()

Example

The following sample code provides an example on how to call the GetInstance operation of Cloud Call Center. Before you call this operation, you must install Cloud Call Center SDK for Go.

from alibabacloud_credentials.client import Client as CredClient
from alibabacloud_credentials.models import Config as CredConfig
from alibabacloud_ccc20200701.client import Client as CCC20200701Client
from alibabacloud_ccc20200701 import models as ccc20200701_models
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions

# Use a bearer token to initialize the Credentials client. 
credentialsConfig = CredConfig(
    type='bearer',  # Specify the type of the credential. 
    bearer_token='<bearer_token>',  # Specify the bearer token that is automatically generated by the server. The bearer token has a validity period. 
)
credentialsClient = CredClient(credentialsConfig)
config = Config(credential=credentialsClient)

# Specify the endpoint of ECS. 
config.endpoint = 'ccc.cn-shanghai.aliyuncs.com'
# Use the Credentials client to initialize the Cloud Call Center Client. 
cccClient = CCC20200701Client(config)

request = ccc20200701_models.GetInstanceRequest(
    instance_id='ccc-test'
)
# Initialize the runtime configurations. 
runtime_options = RuntimeOptions()
response = cccClient.get_instance_with_options(request, runtime_options)
print(response.to_map())

Default credential provider chain

If you want to use different types of credentials in the development and production environments of your application, you generally need to obtain the environment information from the code and write code branches to obtain different credentials for the development and production environments. The default credential provider chain of Alibaba Cloud Credentials for Java allows you to use the same code to obtain credentials for different environments based on configurations independent of the application. If you use cred = CredClient() to initialize a Credentials client without specifying an initialization method, the Credentials tool obtains the credential information in the following order:

1. Obtain the credential information from environment variables

If no credential information is found in the system attributes, the Credentials continues to check the environment variables.

  • If both the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are specified, they are used as the default credential.

  • If ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and ALIBABA_CLOUD_SECURITY_TOKEN are specified, the STS token is used as the default credential.

2. Obtain the credential information by using the RAM role of an OIDC IdP

If no credentials with a higher priority are found, the Credentials tool checks the following environment variables that are related to the RAM role of the OIDC IdP:

  • ALIBABA_CLOUD_ROLE_ARN: the ARN of the RAM role.

  • ALIBABA_CLOUD_OIDC_PROVIDER_ARN: the ARN of the OIDC IdP.

  • ALIBABA_CLOUD_OIDC_TOKEN_FILE: the file path of the OIDC token.

If the preceding three environment variables are specified and valid, the Credentials tool uses the environment variables to call the AssumeRoleWithOIDC operation of STS to obtain an STS token as the default credential.

3. Obtain the credential information from a configuration file

Note

Make sure that the version of alibabacloud_credentials is 1.0rc3 or later.

If no credentials with a higher priority are found, the Credentials tool attempts to load the config.json file. Default file path:

  • Linux: ~/.aliyun/config.json

  • Windows: C:\Users\USER_NAME\.aliyun\config.json

If the config.json file exists, the Credentials tool initializes a Credentials client by using the credential information that is specified by the current parameter in the config.json file. You can also specify the ALIBABA_CLOUD_PROFILE environment variable to specify the credential information. For example, you can set the ALIBABA_CLOUD_PROFILE environment variable to client1.

The mode parameter in the config.json file specifies the method that is used to obtain the credential information. Valid values:

  • AK: uses the AccessKey pair of a RAM user to obtain the credential information.

  • RamRoleArn: uses the ARN of a RAM role to obtain the credential information.

  • EcsRamRole: uses the RAM role attached to an ECS instance to obtain the credential information.

  • OIDC: uses the ARN of an OIDC IdP and the OIDC token file to obtain the credential information.

  • ChainableRamRoleArn: uses a role chain and specifies an access credential in another JSON file to obtain the credential information.

Configuration example:

{
	"current": "default",
	"profiles": [
		{
			"name": "default",
			"mode": "AK",
			"access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
			"access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>"
		},
		{
			"name":"client1",
			"mode":"RamRoleArn",
			"access_key_id":"<ALIBABA_CLOUD_ACCESS_KEY_ID>",
			"access_key_secret":"<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
			"ram_role_arn":"<ROLE_ARN>",
			"ram_session_name":"<ROLE_SESSION_NAME>",
			"expired_seconds":3600
		},
		{
			"name":"client2",
			"mode":"EcsRamRole",
			"ram_role_name":"<RAM_ROLE_ARN>"
		},
		{
			"name":"client3",
			"mode":"OIDC",
			"oidc_provider_arn":"<OIDC_PROVIDER_ARN>",
			"oidc_token_file":"<OIDC_TOKEN_FILE>",
			"ram_role_arn":"<ROLE_ARN>",
			"ram_session_name":"<ROLE_SESSION_NAME>",
			"expired_seconds":3600
		},
		{
			"name":"client4",
			"mode":"ChainableRamRoleArn",
			"source_profile":"<PROFILE_NAME>",
			"ram_role_arn":"<ROLE_ARN>",
			"ram_session_name":"<ROLE_SESSION_NAME>",
			"expired_seconds":3600
		}
	]
}

4. Obtain the credential information by using the RAM role of an ECS instance

By default, if no credential that has a higher priority exists, the Credential tool accesses the metadata server of ECS in security hardening mode (IMDSv2) to obtain the STS token of the RAM role used by the ECS instance and uses the STS token as the default credential. The program automatically access the metadata server of ECS to obtain the name of the RAM role (RoleName) and then obtains the credential. Two requests are sent in this process. If you want to send only one request, add the ALIBABA_CLOUD_ECS_METADATA environment variable to specify the name of the RAM role. If an exception occurs in the security hardening mode (IMDSv2), the Credentials tool obtains the access credential in normal mode. You can also configure the ALIBABA_CLOUD_IMDSV1_DISABLED environment variable to specify an exception handling logic. Valid values of the environment variable:

  1. false: The Credentials tool continues to obtain the access credential in normal mode.

  2. true: The exception is thrown and the Credentials tool continues to obtain the access credential in security hardening mode.

The configurations for the metadata server determine whether the server supports the security hardening mode (IMDSv2).

In addition, you can set the ALIBABA_CLOUD_ECS_METADATA_DISABLED=true environment variable to disable access from the Credentials tool to the metadata server of ECS.

5. Obtain the credential information based on a URI

If no valid credential is obtained by using the preceding methods, the Credentials tool checks the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. If this environment variable exists and specifies a valid URI, the Credentials tool initiates an HTTP requests to obtain an STS token as the default credential.

Switch between credentials

You can use the following method to use different credentials to call different API operations in your application.

Use multiple Credentials clients

Initialize multiple Credentials clients to pass different credentials to different request clients.

import os

from alibabacloud_credentials.client import Client
from alibabacloud_credentials.models import Config

config1 = Config(
    type='access_key',
    access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
)
cred1 = Client(config1)

config2 = Config(
    type='sts',
    access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    security_token=os.environ.get('ALIBABA_CLOUD_SECURITY_TOKEN')
)
cred2 = Client(config2)

Use the AuthUtils class

If you initialize a Credentials client by using the credential information recorded in a configuration file, you can use the auth_util.client_type parameter to switch between different credentials. To query the size of cold data, you can execute the following sample statement:

from alibabacloud_credentials.utils import auth_util
from alibabacloud_credentials.client import Client

# If you do not specify the clientType property of the AuthUtils class, default is used. 
credentialClient = Client()
# Switch to the client1 credential.
auth_util.client_type = "client1"
credentialClient1 = Client()
# Switch to the client2 credential.
auth_util.client_type = "client2"
credentialClient2 = Client()

Related operations