Credential security, validity, and rotation requirements vary by deployment environment. Choose a credential configuration method based on your use case to balance security and maintenance costs.
Choose a credential type
Tablestore supports multiple credential types, including AccessKey pairs and STS tokens. Each method targets a specific deployment scenario and SDK availability.
|
Credential method |
Use case |
Requires a pre-configured AccessKey pair or STS token |
Underlying credential |
Validity |
Rotation or refresh method |
SDK support |
|
Applications that run in secure, stable environments with low risk of external attacks and do not require frequent credential rotation for long-term access to cloud services. |
Yes |
AccessKey pair |
Long-term |
Manual rotation |
Java, Go, Python, Node.js, .NET, PHP |
|
|
Applications that run in untrusted environments and require control over access validity and permissions. |
Yes |
STS token |
Temporary |
Manual refresh |
Java, Go, Python, Node.js, PHP |
|
|
Applications that require cross-account authorization to access cloud services. |
Yes |
STS token |
Temporary |
Automatic refresh |
Java |
|
|
Applications that run on Elastic Compute Service (ECS) instances, Elastic Container Instance (ECI) instances, or Container Service for Kubernetes (ACK) worker nodes. |
No |
STS token |
Temporary |
Automatic refresh |
Java |
|
|
Untrusted applications that run on ACK worker nodes. |
No |
STS token |
Temporary |
Automatic refresh |
Java |
|
|
Applications that run in Function Compute. |
No |
STS token |
Temporary |
No refresh required |
Java, Python |
|
|
Applications that need to obtain credentials from an external system. |
No |
STS token |
Temporary |
Automatic refresh |
Java |
|
|
Applications that run in environments at risk of AccessKey pair leaks and require frequent credential rotation for long-term access to cloud services. |
No |
AccessKey pair |
Long-term |
Automatic rotation |
Java |
|
|
Custom credential retrieval for cases where none of the preceding methods meet your requirements. |
Custom |
Custom |
Custom |
Custom |
Java |
|
|
AI application integration with Knowledge Store and Memory Store, without the need to manage AccessKey pairs. |
No |
API key |
Configurable |
Manual revocation and recreation |
Python, TypeScript |
Configure credentials
After you choose a credential type, see the corresponding section for step-by-step instructions and code examples.
Use an AccessKey pair of a RAM user
Configure credentials with the AccessKey pair (AccessKey ID and AccessKey Secret) of a RAM user. This method requires manual AccessKey pair maintenance and poses a higher security risk.
An Alibaba Cloud account has full permissions on all resources. If the AccessKey pair of an Alibaba Cloud account is leaked, all resources in the account are at risk. Use the AccessKey pair of a RAM user with the minimum required permissions. To obtain the AccessKey pair of a RAM user, see Access Tablestore with a RAM user's AccessKey pair.
Configure the AccessKey pair with environment variables or static credentials.
Environment variables
-
Configure environment variables. After you set them, restart your IDE, CLI, desktop applications, and background services to load the updated environment variables.
Linux
-
Append the environment variables to the
~/.bashrcfile.echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc -
Apply the changes.
source ~/.bashrc -
Verify the environment variables.
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
macOS
-
Check the default shell type.
echo $SHELL -
Proceed based on the default shell type.
Zsh
-
Append the environment variables to the
~/.zshrcfile.echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Apply the changes.
source ~/.zshrc -
Verify the environment variables.
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
Bash
-
Append the environment variables to the
~/.bash_profilefile.echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Apply the changes.
source ~/.bash_profile -
Verify the environment variables.
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
-
Windows
CMD
-
Set the environment variables in CMD.
setx TABLESTORE_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx TABLESTORE_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET" -
Restart CMD and run the following commands to verify that the environment variables are set.
echo %TABLESTORE_ACCESS_KEY_ID% echo %TABLESTORE_ACCESS_KEY_SECRET%
PowerShell
-
Set the environment variables 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) -
Verify the environment variables.
[Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
-
Pass the credential information with environment variables.
Java
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 credentials from environment variables EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Use credentialsProvider for subsequent operations... } { // Example 2: Obtain the accessKeyId and accessKeySecret from environment variables final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID"); final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET"); // Use the accessKeyId and accessKeySecret for subsequent operations... } } }Python
# -*- coding: utf-8 -*- import os access_key_id = os.getenv("TABLESTORE_ACCESS_KEY_ID") access_key_secret = os.getenv("TABLESTORE_ACCESS_KEY_SECRET")Go
accessKeyId := os.Getenv("TABLESTORE_ACCESS_KEY_ID") accessKeySecret := os.Getenv("TABLESTORE_ACCESS_KEY_SECRET")Node.js
var accessKeyId = process.env.TABLESTORE_ACCESS_KEY_ID; var secretAccessKey = process.env.TABLESTORE_ACCESS_KEY_SECRET;PHP
$accessKeyId = getenv('TABLESTORE_ACCESS_KEY_ID'); $accessKeySecret = getenv('TABLESTORE_ACCESS_KEY_SECRET');.NET
// Obtain access credentials from environment variables. var AccessKeyId = Environment.GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID"); var AccessKeySecret = Environment.GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET");
Static credentials
Reference credentials from variables in your code. These variables are populated with actual credential values from environment variables, configuration files, or other external data sources at runtime.
The following example uses static credentials from a configuration file.
-
Create a configuration file named
config.ini.[configName] TABLESTORE_ACCESS_KEY_ID = your_access_key_id TABLESTORE_ACCESS_KEY_SECRET = your_access_key_secret -
Pass the credential information from the configuration file.
Java
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(); // Set the path to 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 ID and AccessKey Secret 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... } }Python
# -*- coding: utf-8 -*- import configparser # Read the configuration file config = configparser.ConfigParser() # Assume 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')Go
// 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()PHP
try { // Read the configuration file. Assume 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 credentials
Configure credentials with the temporary identity credentials (AccessKey ID, AccessKey Secret, and Security Token) obtained from Security Token Service (STS). This method requires manual STS token maintenance and poses a higher security risk. To access Tablestore multiple times with temporary credentials, you must manually refresh the STS token. To obtain STS temporary credentials, see Use STS temporary credentials to access Tablestore.
Configure STS temporary credentials with environment variables or static credentials.
Environment variables
-
Configure environment variables. After you set them, restart your IDE, CLI, desktop applications, and background services to load the updated environment variables.
Linux
-
Append the environment variables to the
~/.bashrcfile.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 -
Apply the changes.
source ~/.bashrc -
Verify the environment variables.
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET echo $TABLESTORE_SESSION_TOKEN
macOS
-
Check the default shell type.
echo $SHELL -
Proceed based on the default shell type.
Zsh
-
Append the environment variables to the
~/.zshrcfile.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 -
Apply the changes.
source ~/.zshrc -
Verify the environment variables.
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET echo $TABLESTORE_SESSION_TOKEN
Bash
-
Append the environment variables to the
~/.bash_profilefile.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 -
Apply the changes.
source ~/.bash_profile -
Verify the environment variables.
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET echo $TABLESTORE_SESSION_TOKEN
-
Windows
CMD
-
Set the environment variables in CMD.
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" -
Restart CMD and run the following commands to verify that the environment variables are set.
echo %TABLESTORE_ACCESS_KEY_ID% echo %TABLESTORE_ACCESS_KEY_SECRET% echo %TABLESTORE_SESSION_TOKEN%
PowerShell
-
Set the environment variables 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) -
Verify the environment variables.
[Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("TABLESTORE_SESSION_TOKEN", [EnvironmentVariableTarget]::User)
-
-
Pass the credential information with environment variables.
Java
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 credentials from environment variables EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Use credentialsProvider for subsequent operations... } { // Example 2: Obtain the accessKeyId, accessKeySecret, and securityToken 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 accessKeyId, accessKeySecret, and securityToken for subsequent operations... } } }Python
# -*- 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")Go
accessKeyId := os.Getenv("TABLESTORE_ACCESS_KEY_ID") accessKeySecret := os.Getenv("TABLESTORE_ACCESS_KEY_SECRET") securityToken := os.Getenv("TABLESTORE_SESSION_TOKEN")Node.js
var accessKeyId = process.env.TABLESTORE_ACCESS_KEY_ID; var secretAccessKey = process.env.TABLESTORE_ACCESS_KEY_SECRET; var stsToken = process.env.TABLESTORE_SESSION_TOKEN;PHP
$accessKeyId = getenv('TABLESTORE_ACCESS_KEY_ID'); $accessKeySecret = getenv('TABLESTORE_ACCESS_KEY_SECRET'); $securityToken = getenv('TABLESTORE_SESSION_TOKEN');
Static credentials
Reference credentials from variables in your code. These variables are populated with actual credential values from environment variables, configuration files, or other external data sources at runtime.
The following example uses static credentials from a configuration file.
-
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 -
Pass the credential information from the configuration file.
Java
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(); // Set the path of the config.ini file. Replace the path with the actual path. String configFilePath = "config.ini"; // Read the configuration file. FileInputStream input = new FileInputStream(configFilePath); properties.load(input); input.close(); // Obtain the AccessKey ID, AccessKey Secret, and 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... } }Python
# -*- coding: utf-8 -*- import configparser # Read the configuration file config = configparser.ConfigParser() # Assume config.ini is in the same directory as the script. Use the actual path. config.read('config.ini') # Obtain the AccessKey ID, AccessKey Secret, and Security Token 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')Go
// 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, AccessKey Secret, and Security Token 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()PHP
try { // Read the configuration file. Assume 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 credentials with RAMRoleARN. This method uses STS tokens as the underlying credential. When you specify the Alibaba Cloud Resource Name (ARN) of a RAM role, the Credentials tool requests an STS token from STS and automatically refreshes the token before the session expires. You can also assign a value to policy to restrict the RAM role to a smaller set of permissions. This method requires an AccessKey pair, which increases security risk and maintenance effort. To obtain an AccessKey pair, see Create an AccessKey. To obtain a RAMRoleARN, see Create a RAM role.
-
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> -
Configure the AccessKey pair and RAMRoleARN as the 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(); // Credential type. Set the value to ram_role_arn. config.setType("ram_role_arn"); // The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole. You can also set the RoleArn by using the ALIBABA_CLOUD_ROLE_ARN environment variable. config.setRoleArn("<RoleArn>"); // Obtain the AccessKey ID from an environment variable. config.setAccessKeyId(System.getenv().get("TABLESTORE_ACCESS_KEY_ID")); // Obtain the AccessKey Secret from an environment variable. config.setAccessKeySecret(System.getenv().get("TABLESTORE_ACCESS_KEY_SECRET")); // Specify the session name of the RAM role. config.setRoleName("roleSessionName"); // Specify a policy that has fewer permissions. Optional. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"} config.setPolicy("<Policy>"); // Set the validity period of the role session. Optional. 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 for subsequent operations... } }
Use ECSRAMRole
Configure credentials with ECSRAMRole. This method uses STS tokens as the underlying credential. ECSRAMRole allows you to attach a role to an ECS instance, an ECI instance, or an ACK worker node. The STS token is automatically refreshed within the instance. This method does not require an AccessKey pair or STS token, which eliminates the risk of manual credential maintenance. To obtain an ECSRAMRole, see Create a RAM role.
-
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> -
Configure ECSRAMRole as the 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(); // Credential type. Set the value to ecs_ram_role. config.setType("ecs_ram_role"); // The name of the RAM role attached to the ECS instance. Optional. If you do not specify this parameter, the role name is automatically retrieved. We recommend that you specify this parameter to reduce the number of requests. config.setRoleName("ECSRAMRole"); // Enable the hardened mode of the ECS instance metadata service (IMDSv2). Optional. We recommend that you enable this parameter to improve the overall system security. 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 for subsequent operations... } }
Use OIDCRoleARN
After you configure a RAM role for an ACK worker node, applications in pods on that node can obtain the STS token of the associated role from the metadata server, similar to applications deployed on ECS instances. However, if untrusted applications run on the cluster, such as customer-submitted code, do not obtain the STS token from the metadata server.
RAM Roles for Service Account (RRSA) provides application-level permission isolation. RRSA allows untrusted applications to securely obtain required credentials without exposing other cloud resources. This method uses STS tokens as the underlying credential. The ACK cluster creates and mounts OIDC token files for different application pods and injects related configuration information into environment variables. The Credentials tool reads the configuration information from environment variables and calls the AssumeRoleWithOIDC operation of STS to obtain the STS token of the bound role. This method does not require an AccessKey pair or STS token, which eliminates the risk of manual credential maintenance. For more information, see Use RRSA for pod-level access control.
-
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> -
Configure the OIDC RAM role as the 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 OidcRoleArnDemoTest { public static void main(String[] args) { com.aliyun.credentials.models.Config config = new com.aliyun.credentials.models.Config(); // Credential type. Set the value to oidc_role_arn. config.setType("oidc_role_arn"); // The ARN of the RAM role. You can also set the RoleArn by using the ALIBABA_CLOUD_ROLE_ARN environment variable. config.setRoleArn("<RoleArn>"); // The ARN of the OIDC provider. You can also set the OidcProviderArn by using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable. config.setOidcProviderArn("<OidcProviderArn>"); // The path of the OIDC token file. You can also set the OidcTokenFilePath by using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable. config.setOidcTokenFilePath("<OidcTokenFilePath>"); // The role session name. You can also set the RoleSessionName by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. config.setRoleSessionName("<RoleSessionName>"); // Specify a policy that has fewer permissions. Optional. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"} config.setPolicy("<Policy>"); // Set the session expiration time. 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 for subsequent operations... } }
Use credentials from the Function Compute context
Configure credentials from the Function Compute context. This method uses STS tokens as the underlying credential. Function Compute assumes the service role configured for the function to obtain an STS token, which is passed to the function code through the Credentials context parameter. The token is valid for 36 hours and cannot be changed. The maximum execution time of a function is 24 hours, so the token does not expire during execution and does not require refreshing. This method does not require an AccessKey pair or STS token, which eliminates the risk of manual credential maintenance. To grant Function Compute the permissions to access Tablestore, see Use a function role to access other cloud services.
Java
-
Add the Function Compute context dependency.
<!-- 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> -
Initialize a credentials provider with the credentials from 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 credential information. Before you run the code, make sure that the service associated with the function is configured with a role that has Tablestore permissions. We recommend that you use the AliyunFCDefaultRole role. Credentials creds = context.getExecutionCredentials(); // Create a credential provider by using the obtained credentials. CredentialsProvider credentialsProvider = new DefaultCredentialProvider(creds.getAccessKeyId(), creds.getAccessKeySecret(), creds.getSecurityToken()); // Use credentialsProvider for subsequent operations... outputStream.write(new String("done").getBytes()); } }
Python
Obtain temporary access credentials from the Function Compute context.
# -*- coding: utf-8 -*-
def handler(event, context):
# Obtain credential information. Before you run the code, make sure that the service associated with the function
# has a role configured with Tablestore permissions. 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
# Subsequent operations...
return 'success'
Use CredentialsURI
Configure credentials with a CredentialsURI. This method uses STS tokens as the underlying credential. The Credentials tool obtains an STS token from the URI that you provide and initializes the credentials client. This method does not require an AccessKey pair or STS token, which eliminates the risk of manual credential maintenance. The backend service that responds to the CredentialsURI must implement automatic STS token refresh logic to ensure that the application can always obtain valid credentials.
-
To allow the Credentials tool to parse and use the 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" }
-
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> -
Configure the CredentialsURI as the 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 CredentialsUriDemoTest { public static void main(String[] args) { com.aliyun.credentials.models.Config config = new com.aliyun.credentials.models.Config(); // Credential type. Set the value to credentials_uri. config.setType("credentials_uri"); // The URI used to obtain credentials. Format: http://local_or_remote_uri/ 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 for subsequent operations... } }
Use an automatically rotated AccessKey pair
Configure credentials with a ClientKey. With a ClientKey, Key Management Service (KMS) automatically rotates the managed RAM user AccessKey pair on a periodic schedule, converting a static AccessKey pair into a dynamic one and reducing the risk of leaks. KMS also supports immediate rotation, which allows you to quickly replace the AccessKey pair if it is leaked. This method does not require manual AccessKey pair maintenance, which reduces security risks and maintenance effort.
-
Add the secrets client dependency.
<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> -
Create a configuration file named
secretsmanager.properties.# Access credential type. Set the value to client_key. credentials_type=client_key # Decryption password for the Client Key. You can read the password from an environment variable or a file. Configure only one of the following settings. 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> # Path to the private key file of the Client Key client_key_private_key_path=<your client key private key file path> # Region ID of the associated KMS service cache_client_region_id=[{"regionId":"<regionId>"}] -
Pass the credential information from the configuration file.
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 for subsequent operations... } }
Use custom credentials
If none of the preceding credential configuration methods meet your requirements, implement the Credential Providers interface to customize how credentials are provided. If the underlying implementation uses STS tokens, you must support credential refresh.
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 accessKeySecret = null;
// Initialize the variable.
// String token = null;
@Override
public void setCredentials(ServiceCredentials credentials) {
}
@Override
public ServiceCredentials getCredentials() {
//TODO
// Implement custom logic to obtain credentials.
// Return long-lived credentials: access_key_id and access_key_secret.
return new DefaultCredentials(accessKeyId, accessKeySecret);
// Return temporary credentials: access_key_id, access_key_secret, and token.
// For temporary credentials, refresh the credentials based on the expiration time.
// return new DefaultCredentials(accessKeyId, accessKeySecret, token);
}
};
// Use credentialsProvider for subsequent operations...
}
}