To use Tablestore SDK for Java to initiate a request, you must configure access credentials. Alibaba Cloud services use access credentials to verify identity information and access permissions. You can select different types of access credentials based on your authentication and authorization requirements.
Prerequisites
Tablestore SDK for Java is installed. For more information, see Install Tablestore SDK for Java.
Select an initialization method
Select a credential provider
Tablestore supports multiple methods to initialize a credential provider. You can select a suitable method based on the authentication and authorization requirements of your actual scenario.
Initialization method | Scenario | AccessKey pair or STS token required | Underlying logic | Credential validity period | Credential rotation or refresh method |
Applications are deployed and run in a secure and stable environment that is not vulnerable to external attacks and need to access cloud services for a long period of time without frequent credential rotation. | Yes | AccessKey pair | Long-term | Manual rotation | |
Applications are deployed and run in an environment in which the AccessKey pair may be leaked and require frequent rotation of the access credentials to access cloud services for a long period of time. | No | AccessKey pair | Long-term | Automatic rotation | |
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 | |
Applications need to be authorized to access cloud services, such as cross-account access. | Yes | STS token | Temporary | Automatic refresh | |
Applications are deployed and run on Elastic Compute Service (ECS) instances, elastic container instances, or Container Service for Kubernetes (ACK) worker nodes. | No | STS token | Temporary | Automatic refresh | |
Untrusted applications are deployed and run on ACK worker nodes. | No | STS token | Temporary | Automatic refresh | |
Method 7: 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 | Refresh not required |
Applications require access credentials from external systems. | No | STS token | Temporary | Automatic refresh | |
If none of the preceding methods meet your requirements, you can specify a custom method to obtain access credentials. | Custom | Custom | Custom | Custom |
Method 1: Use an AccessKey pair
If your application is deployed in a secure and stable environment that is not vulnerable to external attacks and requires long-term access to Tablestore without frequent credential rotation, you can use an AccessKey pair of your Alibaba Cloud account or a Resource Access Management (RAM) user to initialize a credential provider. An AccessKey pair consists of an AccessKey ID and an AccessKey secret. Take note that this method requires you to manually maintain an AccessKey pair. This poses security risks and increases maintenance complexity. For more information about how to obtain an AccessKey pair, see Use AccessKey pairs of RAM users to initiate requests.
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 the AccessKey pair of a RAM user that is granted permissions based on the principle of least privilege to initialize a credential provider.
Environment variables
Use the AccessKey pair to specify environment variables.
Mac OS X, Linux, and Unix
export TABLESTORE_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> export TABLESTORE_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>
Windows
Open Command Prompt and run the following commands as the administrator:
setx TABLESTORE_ACCESS_KEY_ID <ALIBABA_CLOUD_ACCESS_KEY_ID> /m setx TABLESTORE_ACCESS_KEY_SECRET <ALIBABA_CLOUD_ACCESS_KEY_SECRET> /m
Use environment variables to pass credentials.
NoteAfter you specify the environment variables, you may need to restart the relevant services or development tools such as Integrated Development Environment (IDE) to ensure that the new settings are applied as expected.
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 { // Obtain access credentials from environment variables. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Use credentialsProvider for subsequent operations. } }
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 a configuration file to pass credentials.
Create a configuration file named
config.ini
.[credentials] accessKeyId = <ALIBABA_CLOUD_ACCESS_KEY_ID> accessKeySecret = <ALIBABA_CLOUD_ACCESS_KEY_SECRET>
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 configuration file. 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("accessKeyId"); String accessKeySecret = properties.getProperty("accessKeySecret"); CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret); // Use credentialsProvider for subsequent operations. } }
Method 2: Use an AccessKey pair that automatically rotates
If your application needs to access Tablestore for a long period of time while the AccessKey pair is posed to risks in the runtime environment, you need to manually rotate the AccessKey pair in a frequent manner. In this case, you can use a client key to initialize the credential provider. The underlying logic of this method is to use an AccessKey pair to access Tablestore resources. After you use a client key, Key Management Service (KMS) regularly rotates the AccessKey pair of a managed RAM user and dynamically changes the static AccessKey pair of a RAM user. This reduces the risk of AccessKey pair leaks. KMS also supports immediate rotation to quickly replace a leaked AccessKey pair. This frees you from manually maintaining an AccessKey pair and reduces security risks and maintenance complexity. For more information about how to obtain a client key, see Create an AAP.
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>
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>"}]
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 for subsequent operations. } }
Method 3: Use an STS token
If your application needs to temporarily access Tablestore, you can use temporary access credentials, which consist of an AccessKey pair and a Security Token Service (STS) token to initialize a credential provider. Take note that this method requires you to manually maintain an STS token. This poses security risks and increases maintenance complexity. If you want to access Tablestore multiple times, you must manually refresh the STS token. For more information about how to obtain an STS token, see Use an STS token to initiate requests.
Environment variables
Use temporary access credentials to specify environment variables.
Mac OS X, Linux, and Unix
export TABLESTORE_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> export TABLESTORE_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET> export TABLESTORE_SESSION_TOKEN=<ALIBABA_CLOUD_SECURITY_TOKEN>
Windows
Open Command Prompt and run the following commands as the administrator:
setx TABLESTORE_ACCESS_KEY_ID <ALIBABA_CLOUD_ACCESS_KEY_ID> /m setx TABLESTORE_ACCESS_KEY_SECRET <ALIBABA_CLOUD_ACCESS_KEY_SECRET> /m setx TABLESTORE_SESSION_TOKEN <ALIBABA_CLOUD_SECURITY_TOKEN> /m
Use environment variables to pass credentials.
NoteAfter you specify the environment variables, you may need to restart the relevant services or development tools such as IDE to ensure that the new settings are applied as expected.
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 { // Obtain access credentials from environment variables. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Use credentialsProvider for subsequent operations. } }
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 a configuration file to pass credentials.
Create a configuration file named
config.ini
.[credentials] accessKeyId = <ALIBABA_CLOUD_ACCESS_KEY_ID> accessKeySecret = <ALIBABA_CLOUD_ACCESS_KEY_SECRET> securityToken = <ALIBABA_CLOUD_SECURITY_TOKEN>
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 configuration file. String configFilePath = "config.ini"; // Read the configuration file. FileInputStream input = new FileInputStream(configFilePath); properties.load(input); input.close(); // Obtain the AccessKey pair and STS token from the configuration file. String accessKeyId = properties.getProperty("accessKeyId"); String accessKeySecret = properties.getProperty("accessKeySecret"); String securityToken = properties.getProperty("securityToken"); CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret, securityToken); // Use credentialsProvider for subsequent operations. } }
Method 4: Use an AccessKey pair and a RAM role
If your application needs to be authorized to access Tablestore, such as accessing the Tablestore resources of another Alibaba Cloud account, you can use an AccessKey pair and a RAM role to initialize a credential provider. The underlying logic of this method is to use an STS token to configure access credentials. The Credentials tool obtains an STS token based on the specified Alibaba Cloud Resource Name (ARN) of a RAM role and automatically refreshes the STS token before the session expires. You can specify the Policy
parameter to limit the permissions granted to the RAM role. Take note that this method requires an AccessKey pair, which poses security risks and increases maintenance complexity. For more information about how to obtain an AccessKey pair, see CreateAccessKey. For more information about how to obtain the ARN of a RAM role, see CreateRole.
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>
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"); // Obtain the ARN of the RAM role from the environment variable. config.setRoleArn(System.getenv().get("ALIBABACLOUD_STS_ROLE_ARN")); // Obtain the AccessKey ID from the environment variable. config.setAccessKeyId(System.getenv().get("OTS_AK_ENV")); // Obtain the AccessKey secret from the environment variables. config.setAccessKeySecret(System.getenv().get("OTS_SK_ENV")); // 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 for subsequent operations. } }
Method 5: Use the RAM role of an ECS instance
If your application runs on an ECS instance, an elastic container instance, or an ACK worker node, we recommend that you use the RAM role of the ECS instance to initialize a credential provider. The underlying logic of this method is to use an STS token to configure access credentials. You can attach a RAM role to an ECS instance, an elastic container instance, or an ACK worker node to automatically refresh the STS token on the instance. This method eliminates the risks that may arise when you manually maintain an AccessKey pair or an STS token. For more information about how to obtain the RAM role, see CreateRole.
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>
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 specify this parameter, the system automatically searches for a RAM role. We recommend that you specify 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 specify 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 for subsequent operations. } }
Method 6: Use the RAM role of an OIDC IdP
After a RAM role is configured on an ACK worker node, the application in a pod on the node can obtain the STS token of the attached role by using the metadata server in the same manner as an application deployed on an ECS instance does. 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 unavailable 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, 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 to configure access credentials. ACK creates and mounts corresponding OpenID Connect (OIDC) token files for different application pods, and passes relevant configuration information to environment variables. The Credentials tool obtains the configuration information from environment variables and calls the AssumeRoleWithOIDC operation of STS to obtain the STS token of attached roles. This method eliminates the risks that may arise when you manually maintain an AccessKey pair or an STS token. For more information, see Use RRSA to authorize different pods to access different cloud services.
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>>
Use the RAM role 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"); // Obtain the temporary AccessKey ID from the environment variable. config.setAccessKeyId(System.getenv().get("OTS_AK_ENV")); // Obtain temporary AccessKey secret from the environment variable. config.setAccessKeySecret(System.getenv().get("OTS_SK_ENV")); // Obtain the temporary STS token from the environment variable. config.setSecurityToken(System.getenv().get("OTS_SESSION_TOKEN")); // Specify the ARN of the RAM role, which is the ID of the RAM role to be assumed. config.setRoleArn(System.getenv("ALIBABA_CLOUD_ROLE_ARN")); // Specify the ARN of the OIDC IdP. config.setOidcProviderArn(System.getenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN")); // Specify the path of the file in which the OIDC token is stored. config.setOidcTokenFilePath(System.getenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE")); // Specify the name of the role session. config.setRoleSessionName("<RoleSessionName>"); // Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}. config.setPolicy("<Policy>"); // Optional. Specify the external ID of the RAM role. // The external ID is provided by the credential provider to avoid proxy confusion. config.setExternalId("<ExternalId>"); // 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 for subsequent operations. } }
Method 7: Use the Credentials parameter in the context of Function Compute
If the function of your application is deployed and run in Function Compute, you can initialize the credential provider by using the Credentials parameter in the context of Function Compute. The underlying logic of this method is to use an STS token to configure access credentials. Function Compute obtains an STS token by assuming a service role based on the role configured for the function. Then, the STS token is passed to your application by using the Credentials parameter in the context of Function Compute. 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 eliminates the risks that may arise when you manually maintain an AccessKey pair or an STS token. For more information about how to grant Function Compute the permissions to access Tablestore, see Grant Function Compute permissions to access other cloud services.
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>
Initializes the credential provider by 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 for subsequent operations. outputStream.write(new String("done").getBytes()); } }
Method 8: Use a credential URI
If your application needs to obtain an Alibaba Cloud credential from an external system to implement flexible credential management and keyless access, you can use a credential URI to initialize a credential provider. The underlying logic of this method is to use an STS token to configure access credentials. The Credentials tool obtains the STS token by using the URI that you specify to initialize the credential client. This method eliminates the risks that may arise when you manually maintain an AccessKey pair or an STS token. Take note that the backend service that provides the credential URI response must automatically refresh the STS token to ensure that your application can always obtain a valid credential.
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" }
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 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 for subsequent operations. } }
Method 9: Use custom access credentials
If none of the preceding methods meet your requirements, you can specify a custom method to obtain access credentials by calling the CredentialsProvider operation. Take note that if the underlying logic is 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 for subsequent operations.
}
}
What to do next
After the credential provider is initialized, you need to use the credential provider to create an OTSClient instance. For more information, see Initialize an OTSClient instance.