All Products
Search
Document Center

Tablestore:Configure access credentials

Last Updated:Jul 16, 2025

Tablestore supports multiple types of access credentials. You can select the appropriate access credential based on the authentication and authorization requirements of your business scenario.

Access credential selection

Tablestore supports access credential types such as AccessKey (AK) and STS token, along with multiple configuration methods. The following table describes the applicable scenarios and SDK support for different configuration methods.

Access credential configuration method

Scenarios

AccessKey pair or STS token required

Underlying Implementation Credentials

Credential validity period

Credential rotation or refresh method

SDK support

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 to access cloud services for a long period of time without frequent credential rotation

Yes

AK

Long-term

Manual rotation

Java, Go, Python, Node.js, .NET, PHP

Use STS temporary access credentials

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

Yes

STS Token

Temporary

Manual refresh

Java, Go, Python, Node.js, PHP

Use RAMRoleARN

Applications need to be authorized to access cloud services, such as cross-account access to cloud services

Yes

STS Token

Temporary

Automatic refresh

Java

Use ECSRAMRole

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

No

STS Token

Temporary

Automatic refresh

Java

Use OIDCRoleARN

Untrusted applications are deployed and run on Container Service for Kubernetes worker nodes

No

STS Token

Temporary

Automatic refresh

Java

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

Java, Python

Use CredentialsURI

Applications require access credentials from external systems

No

STS Token

Temporary

Automatic refresh

Java

Use an AccessKey pair that automatically rotates

Applications are deployed and run in an environment in which the AccessKey pair has high risks of leakage and require frequent rotation of the access credentials

No

AK

Long-term

Automatic rotation

Java

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

Java

Access credential configuration methods

Use the AccessKey pair of a RAM user

Configure access credentials using the AccessKey pair (AccessKey ID and AccessKey secret) of a RAM user. This method requires you to manually maintain an AccessKey pair, which poses security risks and increases maintenance complexity.

Important

An Alibaba Cloud account has full permissions on resources within the account. Leaks of the Alibaba Cloud account AccessKey pair pose critical security threats. Therefore, we recommend that you use the AccessKey pair of a RAM user that is granted the minimum required permissions. For information about how to obtain the AccessKey pair of a RAM user, see Use the AccessKey pair of a RAM user to access Tablestore.

When you use this method, you can configure credentials using environment variables or static credentials. The following items describe the detailed configurations:

Environment variables

  1. Configure environment variables. After you configure the environment variables, restart or refresh your compilation and runtime environment, including IDE, command-line interface, other desktop applications, and backend services to ensure that the latest system environment variables are successfully loaded.

    Linux
    1. Run the following commands in the command-line interface to append environment variable settings to the ~/.bashrc file.

      echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export TABLESTORE_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 $TABLESTORE_ACCESS_KEY_ID
      echo $TABLESTORE_ACCESS_KEY_SECRET
    macOS
    1. Run the following command in the terminal to check the default shell type:

      echo $SHELL
    2. Perform operations based on the default shell type.

      Zsh
      1. Run the following commands to append environment variable settings to the ~/.zshrc file.

        echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
        echo "export TABLESTORE_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 $TABLESTORE_ACCESS_KEY_ID
        echo $TABLESTORE_ACCESS_KEY_SECRET
      Bash
      1. Run the following commands to append environment variable settings to the ~/.bash_profile file.

        echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
        echo "export TABLESTORE_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 $TABLESTORE_ACCESS_KEY_ID
        echo $TABLESTORE_ACCESS_KEY_SECRET
    Windows
    CMD
    1. Run the following commands in CMD to set environment variables:

      setx TABLESTORE_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx TABLESTORE_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
    2. After you restart CMD, run the following commands to check whether the environment variables take effect:

      echo %TABLESTORE_ACCESS_KEY_ID%
      echo %TABLESTORE_ACCESS_KEY_SECRET%
    PowerShell
    1. Run the following commands in PowerShell:

      [Environment]::SetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
    2. Run the following commands to check whether the environment variables take effect:

      [Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. Use environment variables to pass credentials.

    import com.alicloud.openservices.tablestore.core.auth.CredentialsProviderFactory;
    import com.alicloud.openservices.tablestore.core.auth.EnvironmentVariableCredentialsProvider;
    
    public class AkDemoTest {
        public static void main(String[] args) throws Exception {
            {
                // Example 1: Obtain access credentials from environment variables.
                EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
                // Use credentialsProvider to perform subsequent operations.
            }
            {
                // Example 2: Obtain the AccessKey ID and AccessKey secret from the environment variables.
                final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
                final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
                // Use the AccessKey ID and AccessKey secret to perform subsequent operations.
            }
        }
    }
    accessKeyId := os.Getenv("TABLESTORE_ACCESS_KEY_ID")
    accessKeySecret := os.Getenv("TABLESTORE_ACCESS_KEY_SECRET")
    # -*- coding: utf-8 -*-
    import os
    
    access_key_id = os.getenv("TABLESTORE_ACCESS_KEY_ID")
    access_key_secret = os.getenv("TABLESTORE_ACCESS_KEY_SECRET")
    var accessKeyId = process.env.TABLESTORE_ACCESS_KEY_ID;
    var secretAccessKey = process.env.TABLESTORE_ACCESS_KEY_SECRET;
    // Obtain access credentials from environment variables.
    var AccessKeyId = Environment.GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID");
    var AccessKeySecret = Environment.GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET");
    $accessKeyId = getenv('TABLESTORE_ACCESS_KEY_ID');
    $accessKeySecret = getenv('TABLESTORE_ACCESS_KEY_SECRET');

Static credentials

You can reference credentials by specifying variables in your code. In a runtime environment, the variables are passed by actual credential values from environment variables, configuration files, or other external data sources.

The following procedure describes how to use static credentials in common Tablestore SDKs with a configuration file as an example.

  1. Create a configuration file named config.ini.

    [configName]
    TABLESTORE_ACCESS_KEY_ID = your_access_key_id
    TABLESTORE_ACCESS_KEY_SECRET = your_access_key_secret
  2. Use the configuration file to pass credentials.

    import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
    import com.alicloud.openservices.tablestore.core.auth.DefaultCredentialProvider;
    import java.io.FileInputStream;
    import java.util.Properties;
    
    public class AkDemoTest {
        public static void main(String[] args) throws Exception {
            Properties properties = new Properties();
            // Specify the path of the config.ini file. Use the actual path.
            String configFilePath = "config.ini";
    
            // Read the configuration file.
            FileInputStream input = new FileInputStream(configFilePath);
            properties.load(input);
            input.close();
    
            // Obtain the AccessKey pair from the configuration file.
            String accessKeyId = properties.getProperty("TABLESTORE_ACCESS_KEY_ID");
            String accessKeySecret = properties.getProperty("TABLESTORE_ACCESS_KEY_SECRET");
    
            CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
    
            // Use credentialsProvider for subsequent operations.
        }
    }
    // Read the configuration file. Use the actual path.
    config, err := ini.Load("config.ini")
    if err != nil {
        fmt.Println("Failed to read the configuration file:", err)
    }
    
    // Obtain the AccessKey ID and AccessKey secret from the configuration file.
    access_key_id := config.Section("configName").Key("TABLESTORE_ACCESS_KEY_ID").String()
    access_key_secret := config.Section("configName").Key("TABLESTORE_ACCESS_KEY_SECRET").String()
    # -*- coding: utf-8 -*-
    import configparser
    
    # Read the configuration file
    config = configparser.ConfigParser()
    # Assume that config.ini is in the same directory as the script. Use the actual path.
    config.read('config.ini')
    
    # Obtain the AccessKey ID and AccessKey secret from the configuration file.
    access_key_id = config.get('configName', 'TABLESTORE_ACCESS_KEY_ID')
    access_key_secret = config.get('configName', 'TABLESTORE_ACCESS_KEY_SECRET')
    try {
        // Read the configuration file. Assume that config.ini is in the same directory as the script. Use the actual path.
        $config = parse_ini_file('config.ini');
        // Obtain the AccessKey ID and AccessKey secret.
        $accessKeyId = $config['TABLESTORE_ACCESS_KEY_ID'];
        $accessKeySecret = $config['TABLESTORE_ACCESS_KEY_SECRET'];
    }catch (Exception $e) {
        printf($e->getMessage() . "\n");
        return;
    }

Use STS temporary access credentials

Configure access credentials using temporary access credentials (AccessKey ID, AccessKey secret, and Security Token) obtained from STS. This method requires you to manually maintain an STS token, which poses security risks and increases maintenance complexity. If you want to access Tablestore multiple times, you must manually refresh the STS token. For information about how to obtain STS temporary access credentials, see Use temporary access credentials obtained from STS to access Tablestore.

When you use this method, you can configure temporary access credentials using environment variables or static credentials. The following items describe the detailed configurations:

Environment variables

  1. Configure environment variables. After you configure the environment variables, restart or refresh your compilation and runtime environment, including IDE, command-line interface, other desktop applications, and backend services to ensure that the latest system environment variables are successfully loaded.

    Linux
    1. Run the following commands in the command-line interface to append environment variable settings to the ~/.bashrc file.

      echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_STS_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_STS_ACCESS_KEY_SECRET'" >> ~/.bashrc
      echo "export TABLESTORE_SESSION_TOKEN='YOUR_STS_TOKEN'" >> ~/.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 $TABLESTORE_ACCESS_KEY_ID
      echo $TABLESTORE_ACCESS_KEY_SECRET
      echo $TABLESTORE_SESSION_TOKEN
    macOS
    1. Run the following command in the terminal to check the default shell type:

      echo $SHELL
    2. Perform operations based on the default shell type.

      Zsh
      1. Run the following commands to append environment variable settings to the ~/.zshrc file.

        echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_STS_ACCESS_KEY_ID'" >> ~/.zshrc
        echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_STS_ACCESS_KEY_SECRET'" >> ~/.zshrc
        echo "export TABLESTORE_SESSION_TOKEN='YOUR_STS_TOKEN'" >> ~/.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 $TABLESTORE_ACCESS_KEY_ID
        echo $TABLESTORE_ACCESS_KEY_SECRET
        echo $TABLESTORE_SESSION_TOKEN
      Bash
      1. Run the following commands to append environment variable settings to the ~/.bash_profile file.

        echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_STS_ACCESS_KEY_ID'" >> ~/.bash_profile
        echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_STS_ACCESS_KEY_SECRET'" >> ~/.bash_profile
        echo "export TABLESTORE_SESSION_TOKEN='YOUR_STS_TOKEN'" >> ~/.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 $TABLESTORE_ACCESS_KEY_ID
        echo $TABLESTORE_ACCESS_KEY_SECRET
        echo $TABLESTORE_SESSION_TOKEN
    Windows
    CMD
    1. Run the following commands in CMD to set environment variables:

      setx TABLESTORE_ACCESS_KEY_ID "YOUR_STS_ACCESS_KEY_ID"
      setx TABLESTORE_ACCESS_KEY_SECRET "YOUR_STS_ACCESS_KEY_SECRET"
      setx TABLESTORE_SESSION_TOKEN "YOUR_STS_TOKEN"
    2. After you restart CMD, run the following commands to check whether the environment variables take effect:

      echo %TABLESTORE_ACCESS_KEY_ID%
      echo %TABLESTORE_ACCESS_KEY_SECRET%
      echo %TABLESTORE_SESSION_TOKEN%
    PowerShell
    1. Run the following commands in PowerShell:

      [Environment]::SetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", "YOUR_STS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", "YOUR_STS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("TABLESTORE_SESSION_TOKEN", "YOUR_STS_TOKEN", [EnvironmentVariableTarget]::User)
    2. Run the following commands to check whether the environment variables take effect:

      [Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("TABLESTORE_SESSION_TOKEN", [EnvironmentVariableTarget]::User)
  2. Use environment variables to pass credentials.

    import com.alicloud.openservices.tablestore.core.auth.CredentialsProviderFactory;
    import com.alicloud.openservices.tablestore.core.auth.EnvironmentVariableCredentialsProvider;
    
    public class StsDemoTest {
        public static void main(String[] args) throws Exception {
            {
                // Example 1: Obtain access credentials from environment variables.
                EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
                // Use credentialsProvider for subsequent operations.
            }
            {
                // Example 2: Obtain the AccessKey ID, AccessKey secret, and security token from environment variables.
                final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
                final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
                final String securityToken = System.getenv("TABLESTORE_SESSION_TOKEN");
                // Use the AccessKey ID, AccessKey secret and security token to perform subsequent operations.
            }
        }
    }
    accessKeyId := os.Getenv("TABLESTORE_ACCESS_KEY_ID")
    accessKeySecret := os.Getenv("TABLESTORE_ACCESS_KEY_SECRET")
    securityToken := os.Getenv("TABLESTORE_SESSION_TOKEN")
    # -*- coding: utf-8 -*-
    import os
    
    access_key_id = os.getenv("TABLESTORE_ACCESS_KEY_ID")
    access_key_secret = os.getenv("TABLESTORE_ACCESS_KEY_SECRET")
    sts_token = os.getenv("TABLESTORE_SESSION_TOKEN")
    var accessKeyId = process.env.TABLESTORE_ACCESS_KEY_ID;
    var secretAccessKey = process.env.TABLESTORE_ACCESS_KEY_SECRET;
    var stsToken = process.env.TABLESTORE_SESSION_TOKEN;
    $accessKeyId = getenv('TABLESTORE_ACCESS_KEY_ID');
    $accessKeySecret = getenv('TABLESTORE_ACCESS_KEY_SECRET');
    $securityToken = getenv('TABLESTORE_SESSION_TOKEN');

Static credentials

You can reference credentials by specifying variables in your code. In a runtime environment, the variables are passed by actual credential values from environment variables, configuration files, or other external data sources.

The following procedure describes how to use static credentials in common Tablestore SDKs with a configuration file as an example.

  1. Create a configuration file named config.ini.

    [configName]
    TABLESTORE_ACCESS_KEY_ID = your_sts_access_key_id
    TABLESTORE_ACCESS_KEY_SECRET = your_sts_access_key_secret
    TABLESTORE_SESSION_TOKEN = your_sts_token
  2. Use the configuration file to pass credentials.

    import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
    import com.alicloud.openservices.tablestore.core.auth.DefaultCredentialProvider;
    import java.io.FileInputStream;
    import java.util.Properties;
    
    public class StsDemoTest {
        public static void main(String[] args) throws Exception {
            Properties properties = new Properties();
            // Specify the path of the config.ini file. Use the actual path.
            String configFilePath = "config.ini";
    
            // Read the configuration file.
            FileInputStream input = new FileInputStream(configFilePath);
            properties.load(input);
            input.close();
    
            // Obtain the AccessKey pair and the security token from the configuration file.
            String accessKeyId = properties.getProperty("TABLESTORE_ACCESS_KEY_ID");
            String accessKeySecret = properties.getProperty("TABLESTORE_ACCESS_KEY_SECRET");
            String securityToken = properties.getProperty("TABLESTORE_SESSION_TOKEN");
    
            CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret, securityToken);
            // Use credentialsProvider for subsequent operations.
        }
    }
    // Read the configuration file. Use the actual path.
    config, err := ini.Load("config.ini")
    if err != nil {
        fmt.Println("Failed to read the configuration file:", err)
    }
    
    // Obtain the AccessKey ID and AccessKey secret from the configuration file.
    access_key_id := config.Section("configName").Key("TABLESTORE_ACCESS_KEY_ID").String()
    access_key_secret := config.Section("configName").Key("TABLESTORE_ACCESS_KEY_SECRET").String()
    security_token := config.Section("configName").Key("TABLESTORE_SESSION_TOKEN").String()
    # -*- coding: utf-8 -*-
    import configparser
    
    # Read the configuration file
    config = configparser.ConfigParser()
    # Assume that config.ini is in the same directory as the script. Use the actual path.
    config.read('config.ini')
    
    # Obtain the AccessKey ID and AccessKey secret from the configuration file.
    access_key_id = config.get('configName', 'TABLESTORE_ACCESS_KEY_ID')
    access_key_secret = config.get('configName', 'TABLESTORE_ACCESS_KEY_SECRET')
    security_token = config.get('configName', 'TABLESTORE_SESSION_TOKEN')
    try {
        // Read the configuration file. Assume that config.ini is in the same directory as the script. Use the actual path.
        $config = parse_ini_file('config.ini');
        // Obtain the AccessKey ID, AccessKey secret, and security token.
        $accessKeyId = $config['TABLESTORE_ACCESS_KEY_ID'];
        $accessKeySecret = $config['TABLESTORE_ACCESS_KEY_SECRET'];
        $securityToken = $config['TABLESTORE_SESSION_TOKEN'];
    }catch (Exception $e) {
        printf($e->getMessage() . "\n");
        return;
    }

Use RAMRoleARN

Configure access credentials using RAMRoleARN. The underlying logic of this method is to use an STS token to configure access credentials. By specifying the Alibaba Cloud Resource Name (ARN) of a RAM role, the Credentials tool obtains a security token from STS and automatically refreshes the security token before the session expires. You can also specify the policy parameter to limit the permissions granted to the RAM role. This method requires you to provide an AccessKey pair, which poses security risks and increases maintenance complexity. For information about how to obtain an AccessKey pair, see CreateAccessKey. For information about how to obtain the ARN of a RAM role, see CreateRole.

  1. Add the credentials dependency.

    <!-- https://mvnrepository.com/artifact/com.aliyun/credentials-java -->
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>credentials-java</artifactId>
        <version>0.3.4</version>
    </dependency>
  2. Use an AccessKey pair and the ARN of a RAM role as access credentials.

    import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
    import com.alicloud.openservices.tablestore.core.auth.DefaultCredentials;
    import com.alicloud.openservices.tablestore.core.auth.ServiceCredentials;
    import com.aliyun.credentials.models.CredentialModel;
    
    public class RamRoleArnAkDemoTest {
    
        public static void main(String[] args) {
    
            com.aliyun.credentials.models.Config config = new com.aliyun.credentials.models.Config();
            // Set the credential type to ram_role_arn.
            config.setType("ram_role_arn");
            // Specify the ARN of the RAM role that you want the RAM user to assume. You can specify the ARN of the RAM role using the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole.
            config.setRoleArn("<RoleArn>");
            // Obtain the AccessKey ID from the environment variable.
            config.setAccessKeyId(System.getenv().get("TABLESTORE_ACCESS_KEY_ID"));
            // Obtain the AccessKey secret from the environment variables.
            config.setAccessKeySecret(System.getenv().get("TABLESTORE_ACCESS_KEY_SECRET"));
            // Specify the session name of the RAM role.
            config.setRoleName("roleSessionName");
            // (Optional) Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
            config.setPolicy("<Policy>");
            // (Optional) Specify the validity period of the role session.
            config.setRoleSessionExpiration(3600);
    
            final com.aliyun.credentials.Client credentialsClient = new com.aliyun.credentials.Client(config);
    
            CredentialsProvider credentialsProvider = new CredentialsProvider(){
                @Override
                public void setCredentials(ServiceCredentials credentials) {
                }
    
                @Override
                public ServiceCredentials getCredentials() {
                    CredentialModel credential = credentialsClient.getCredential();
                    return  new DefaultCredentials(credential.getAccessKeyId(), credential.getAccessKeySecret(), credential.getSecurityToken());
                }
            };
            // Use credentialsProvider to perform subsequent operations.
        }
    }

Use ECSRAMRole

Use an ECS RAM role to configure access credentials. The underlying logic of this method is to use an STS token. An ECS RAM role 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 on the instance. This method does not require you to provide an AccessKey pair or an STS token, which eliminates the risks that arise when you manually maintain an AccessKey pair or an STS token. For information about how to obtain an ECS RAM role, see CreateRole.

  1. Add the credentials dependency.

    <!-- https://mvnrepository.com/artifact/com.aliyun/credentials-java -->
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>credentials-java</artifactId>
        <version>0.3.4</version>
    </dependency>
  2. Use the RAM role to provide access credentials.

    import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
    import com.alicloud.openservices.tablestore.core.auth.DefaultCredentials;
    import com.alicloud.openservices.tablestore.core.auth.ServiceCredentials;
    import com.aliyun.credentials.models.CredentialModel;
    
    public class EcsRamRoleDemoTest {
    
        public static void main(String[] args) {
    
            com.aliyun.credentials.models.Config config = new com.aliyun.credentials.models.Config();
            // Set the credential type to ecs_ram_role. 
            config.setType("ecs_ram_role");
            // (Optional) Specify the name of the RAM role that is attached to the ECS instance.  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. 
            config.setRoleName("ECSRAMRole");
            //(Optional) Enable the security hardening mode for the metadata of the ECS instance.  We recommend that you configure this parameter to improve the overall security of the system. 
            config.setEnableIMDSv2(true);
    
            final com.aliyun.credentials.Client credentialsClient = new com.aliyun.credentials.Client(config);
    
            CredentialsProvider credentialsProvider = new CredentialsProvider(){
                @Override
                public void setCredentials(ServiceCredentials credentials) {
                }
    
                @Override
                public ServiceCredentials getCredentials() {
                    CredentialModel credential = credentialsClient.getCredential();
                    return  new DefaultCredentials(credential.getAccessKeyId(), credential.getAccessKeySecret(), credential.getSecurityToken());
                }
            };
            // Use credentialsProvider to perform subsequent operations.
        }
    }

Use OIDCRoleARN

After you configure a RAM role for a worker node in Container Service for Kubernetes (ACK), applications within pods on the node can obtain the STS token for the associated role from the metadata service (Meta Data Server), similar to applications that are deployed on ECS. However, if untrusted applications are deployed on the container cluster, such as applications submitted by your customers for which the code is not available to you, you may not want them to obtain the STS token for the RAM role that is associated with the worker node instance from the metadata service. 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. ACK creates and mounts corresponding service account 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 of 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 configure RAM permissions for a ServiceAccount and implement pod-level permission isolation.

  1. Add the credentials dependency.

    <!-- https://mvnrepository.com/artifact/com.aliyun/credentials-java -->
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>credentials-java</artifactId>
        <version>0.3.4</version>
    </dependency>>
  2. Use the RAM role for an OIDC IdP to provide access credentials.

    public class OidcRoleArnDemoTest {
    
        public static void main(String[] args) {
            com.aliyun.credentials.models.Config config = new com.aliyun.credentials.models.Config();
            // Set the credential type to oidc_role_arn.
            config.setType("oidc_role_arn");
            // Specify the ARN of the RAM role using the ALIBABA_CLOUD_ROLE_ARN environment variable.
            config.setRoleArn("<RoleArn>");
            // Specify the ARN of the OIDC IdP. You can obtain the ARN from the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
            config.setOidcProviderArn("<OidcProviderArn>");
            // Specify the path of the OIDC token file. You can obtain the OIDC token file from the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
            config.setOidcTokenFilePath("<OidcTokenFilePath>");
            // Specify the role session name. You can obtain the role session name from the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
            config.setRoleSessionName("<RoleSessionName>");
            // (Optional) Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
            config.setPolicy("<Policy>");
            // Specify the validity period of the session.
            config.setRoleSessionExpiration(3600);
    
            final com.aliyun.credentials.Client credentialsClient = new com.aliyun.credentials.Client(config);
    
            CredentialsProvider credentialsProvider = new CredentialsProvider() {
                @Override
                public void setCredentials(ServiceCredentials credentials) {
                }
    
                @Override
                public ServiceCredentials getCredentials() {
                    CredentialModel credential = credentialsClient.getCredential();
                    return new DefaultCredentials(credential.getAccessKeyId(), credential.getAccessKeySecret(), credential.getSecurityToken());
                }
            };
            // Use credentialsProvider to perform subsequent operations.
        }
    }

Use the Credentials parameter in the context of Function Compute

Use the Credentials parameter in the Function Compute context to configure access credentials. The underlying logic of this method is to use a Security Token Service (STS) token. Function Compute obtains an STS token by assuming a service role based on the role configured for the function. The STS token is then passed to your application using the Credentials parameter in the context. The STS token is valid for 36 hours. You cannot change its validity period. The maximum execution time of a function is 24 hours. Therefore, you do not need to refresh the STS token because it does not expire when the function is executed. This method does not require you to provide an AccessKey pair or an STS token, which eliminates the risks associated with manually managing these credentials. For more information about how to grant Function Compute permissions to access Tablestore, see Use function roles to grant Function Compute permissions to access other cloud services.

Implementation in Java

  1. Add Function Compute context dependencies.

    <!-- https://mvnrepository.com/artifact/com.aliyun.fc.runtime/fc-java-core -->
    <dependency>
        <groupId>com.aliyun.fc.runtime</groupId>
        <artifactId>fc-java-core</artifactId>
        <version>1.4.1</version>
    </dependency>
  2. Initializes the credential provider using the Credentials parameter in the Function Compute context.

    package example;
    
    import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
    import com.alicloud.openservices.tablestore.core.auth.DefaultCredentialProvider;
    import com.aliyun.fc.runtime.Context;
    import com.aliyun.fc.runtime.Credentials;
    import com.aliyun.fc.runtime.StreamRequestHandler;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    
    public class App implements StreamRequestHandler {
    
        @Override
        public void handleRequest(
                InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
    
            // Obtain the key information. Before you execute the function, make sure that a role is configured for the service to which the function belongs and that the role is granted the permissions to access Tablestore. We recommend that you use the AliyunFCDefaultRole role.
            Credentials creds = context.getExecutionCredentials();
    
            // Use the obtained credential to create a credential provider instance.
            CredentialsProvider credentialsProvider = new DefaultCredentialProvider(creds.getAccessKeyId(), creds.getAccessKeySecret(), creds.getSecurityToken());
    
            // Use credentialsProvider to perform subsequent operations.
    
            outputStream.write(new String("done").getBytes());
        }
    }

Implementation in Python

Use the Credentials parameter in the context of Function Compute to obtain temporary access credentials.

# -*- coding: utf-8 -*-

def handler(event, context):
    # Obtain the key information. Before you execute the function, make sure that a role is configured for the service to which the function belongs and that the role is granted the permissions to access Tablestore. We recommend that you use the AliyunFCDefaultRole role.
    creds = context.credentials

    access_key_id = creds.access_key_id
    access_key_secret = creds.access_key_secret
    security_token = creds.security_token

    # Perform the subsequent operations.

    return 'success'

Use CredentialsURI

Configure access credentials using CredentialsURI. The underlying logic of this method is to use an STS token to configure access credentials. The Credentials tool obtains the STS token using the URI that you specify to initialize the credential client. This method does not require an AccessKey pair or STS token, eliminating the risks associated with manually managing these credentials. 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 response protocol:

    • Response status code: 200

    • Response body structure:

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

    <!-- https://mvnrepository.com/artifact/com.aliyun/credentials-java -->
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>credentials-java</artifactId>
        <version>0.3.4</version>
    </dependency>
  3. Configure the credential URI as the access credential.

    import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
    import com.alicloud.openservices.tablestore.core.auth.DefaultCredentials;
    import com.alicloud.openservices.tablestore.core.auth.ServiceCredentials;
    import com.aliyun.credentials.models.CredentialModel;
    
    public class CredentialsUriDemoTest {
        public static void main(String[] args) {
    
            com.aliyun.credentials.models.Config config = new com.aliyun.credentials.models.Config();
            // Set the credential type to credentials_uri.
            config.setType("credentials_uri");
            // Specify the URI to obtain a credential in the http://local_or_remote_uri/ format.
            config.setCredentialsUri("<local_or_remote_uri>");
    
            final com.aliyun.credentials.Client credentialsClient = new com.aliyun.credentials.Client(config);
    
            CredentialsProvider credentialsProvider = new CredentialsProvider() {
                @Override
                public void setCredentials(ServiceCredentials credentials) {
                }
    
                @Override
                public ServiceCredentials getCredentials() {
                    CredentialModel credential = credentialsClient.getCredential();
                    return new DefaultCredentials(credential.getAccessKeyId(), credential.getAccessKeySecret(), credential.getSecurityToken());
                }
            };
            // Use credentialsProvider to perform subsequent operations.
        }
    }

Use an AccessKey pair that automatically rotates

Configure access credentials using a client key. 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.

  1. Add the credential client dependencies.

    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>alibabacloud-secretsmanager-client</artifactId>
        <version>1.3.7</version>
    </dependency>
    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>aliyun-java-sdk-core</artifactId>
      <version>4.7.0</version>
    </dependency>
  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 obtain the decryption password from environment variables or the configuration 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. Use the configuration file to pass credentials.

    import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
    import com.alicloud.openservices.tablestore.core.auth.DefaultCredentials;
    import com.alicloud.openservices.tablestore.core.auth.ServiceCredentials;
    import com.aliyuncs.kms.secretsmanager.client.SecretCacheClient;
    import com.aliyuncs.kms.secretsmanager.client.SecretCacheClientBuilder;
    import com.aliyuncs.kms.secretsmanager.client.exception.CacheSecretException;
    import com.aliyuncs.kms.secretsmanager.client.model.SecretInfo;
    import org.codehaus.jettison.json.JSONException;
    import org.codehaus.jettison.json.JSONObject;
    
    public class ClientKeyDemoTest {
    
        public static void main(String[] args) throws CacheSecretException {
            final SecretCacheClient client = SecretCacheClientBuilder.newClient();
            CredentialsProvider credentialsProvider = new CredentialsProvider() {
                @Override
                public void setCredentials(ServiceCredentials credentials) {
                }
    
                @Override
                public ServiceCredentials getCredentials() {
                    try {
                        SecretInfo secretInfo = client.getSecretInfo("<secretName>");
                        JSONObject jsonObject = new JSONObject(secretInfo.getSecretValue());
    
                        String accessKeyId = jsonObject.getString("AccessKeyId");
                        String accessKeySecret = jsonObject.getString("AccessKeySecret");
    
                        return new DefaultCredentials(accessKeyId, accessKeySecret);
                    } catch (CacheSecretException | JSONException e) {
                        return null;
                    }
                }
            };
            // Use credentialsProvider to perform 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 Credential Providers operation. If the underlying implementation is based on an STS token, you need to provide credential update support.

import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentials;
import com.alicloud.openservices.tablestore.core.auth.ServiceCredentials;

public class CustomCredentialProviderDemoTest {

    public static void main(String[] args) {

        CredentialsProvider credentialsProvider = new CredentialsProvider(){

            // Initialize the variable.
            String accessKeyId = null;
            // Initialize the variable.
            String accessKeySecrect = null;
            // Initialize the variable.
            // String token = null;

            @Override
            public void setCredentials(ServiceCredentials credentials) {
            }

            @Override
            public ServiceCredentials getCredentials() {
                //TODO
                // Specify a custom method to obtain access credentials.

                // Return long-term access credentials, which consist of an AccessKey ID and an AccessKey secret.
                return new DefaultCredentials(accessKeyId, accessKeySecrect);

                // Return temporary access credentials, which consist of an AccessKey ID, an AccessKey secret, and an STS token.
                // Refresh the temporary access credentials based on the expiration time. 
                // return new DefaultCredentials(accessKeyId, accessKeySecrect, token);
            }
        };
        // Use credentialsProvider to perform subsequent operations.
    }
}