Manage access credentials
Alibaba Cloud SDK requires valid credentials to call OpenAPI operations. This topic covers the supported credential types and how to configure them in your code.
Prerequisites
The aliyun-java-auth package is typically installed automatically when you install an Alibaba Cloud product SDK. If the package is not installed or its version is outdated, you can install it using Maven.
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-auth</artifactId>
<version>last-version</version>
</dependency>
For information about the latest version, see aliyun-java-auth.
The content in this topic requires package version 0.3.1-beta or later.
Initialize a credential provider
Multiple credential provider implementations are available. Select the one that best suits your scenario.
-
Storing plaintext AccessKeys in your project poses a security risk. A leaked AccessKey compromises all resources in your account. We recommend that you retrieve AccessKeys from environment variables or configuration files.
-
When you initialize a credential provider, use the singleton pattern. This enables credential caching and prevents traffic throttling and performance degradation caused by redundant API calls.
Default credential provider
The default credential provider retrieves access credentials through a built-in credential provider chain. For more information about the providers and their search order, see Default credential chain.
import com.aliyun.auth.credentials.ICredential;
import com.aliyun.auth.credentials.provider.DefaultCredentialProvider;
import com.aliyun.auth.credentials.provider.EnvironmentVariableCredentialProvider;
import com.aliyun.auth.credentials.provider.SystemPropertiesCredentialProvider;
public class Demo {
public static void main(String[] args) {
DefaultCredentialProvider credentialProvider = DefaultCredentialProvider.builder()
// A custom collection of credential providers. The default provider traverses this collection and stops when it finds valid credentials.
// The default value includes SystemPropertiesCredentialProvider, EnvironmentVariableCredentialProvider, OIDCRoleArnCredentialProvider,
// CLIProfileCredentialsProvider, EcsRamRoleCredentialProvider, and URLCredentialProvider.
.customizeProviders(SystemPropertiesCredentialProvider.create(), EnvironmentVariableCredentialProvider.create())
// Specifies whether to reuse the last successful credential provider. The default value is true. If enabled, the SDK uses the last provider to get credentials instead of traversing the customizeProviders collection again.
.reuseLastProviderEnabled(true)
.build();
// Omit the step of using credentialProvider to initialize AsyncClient...
}
}
System properties credential provider
This provider retrieves access credentials from system properties.
-
If
alibabacloud.accessKeyIdandalibabacloud.accessKeySecretare defined in the system properties, an AccessKey is used as the access credential. -
If
alibabacloud.accessKeyId,alibabacloud.accessKeySecret, andalibabacloud.sessionTokenare defined in the system properties, an STS Token is used as the access credential.
You can add the following JVM parameters when you run the Java program to specify these values:
-Dalibabacloud.accessKeyId=your-access-key-id -Dalibabacloud.accessKeySecret=your-access-key-secret
import com.aliyun.auth.credentials.provider.SystemPropertiesCredentialProvider;
public class Demo {
public static void main(String[] args) {
SystemPropertiesCredentialProvider credentialProvider = SystemPropertiesCredentialProvider.create();
// Omit the step of using credentialProvider to initialize AsyncClient...
}
}
Environment variable credential provider
This provider retrieves access credentials from environment variables:
-
If both ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET exist and are not empty, the provider uses them as the credential.
-
If ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and ALIBABA_CLOUD_SECURITY_TOKEN are all defined, the provider uses an STS Token as the credential.
import com.aliyun.auth.credentials.provider.EnvironmentVariableCredentialProvider;
public class Demo {
public static void main(String[] args) {
EnvironmentVariableCredentialProvider credentialProvider = EnvironmentVariableCredentialProvider.create();
// Omit the step of using credentialProvider to initialize AsyncClient...
}
}
CLI profile credential provider
This provider reads access credentials from the config.json configuration file.
import com.aliyun.auth.credentials.provider.CLIProfileCredentialsProvider;
public class Demo {
public static void main(String[] args) {
CLIProfileCredentialsProvider credentialProvider = CLIProfileCredentialsProvider.builder()
// The profile name. This parameter is optional. If the ALIBABA_CLOUD_PROFILE environment variable is not set, you can use this parameter to specify the profile name to get credentials.
// If this parameter is not specified and the ALIBABA_CLOUD_PROFILE environment variable is not set, the provider uses the profile specified by the 'current' field in config.json.
.profileName("<PROFILE_NAME>")
.build();
// Omit the step of using credentialProvider to initialize AsyncClient...
}
}
To use this provider, you must manually create a config.json file in one of the following paths:
-
Linux:
~/.aliyun/config.json -
Windows:
C:\Users\USER_NAME\.aliyun\config.json
The following example shows the content format:
{
"current": "default",
"profiles": [
{
"name": "default",
"mode": "AK",
"access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
"access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>"
},
{
"name": "client",
"mode": "StsToken",
"access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
"access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
"sts_token": "<SECURITY_TOKEN>"
},
{
"name":"client1",
"mode":"RamRoleArn",
"access_key_id":"<ALIBABA_CLOUD_ACCESS_KEY_ID>",
"access_key_secret":"<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
"ram_role_arn":"<ROLE_ARN>",
"ram_session_name":"<ROLE_SESSION_NAME>",
"expired_seconds":3600
},
{
"name":"client2",
"mode":"EcsRamRole",
"ram_role_name":"<RAM_ROLE_ARN>"
},
{
"name":"client3",
"mode":"OIDC",
"oidc_provider_arn":"<OIDC_PROVIDER_ARN>",
"oidc_token_file":"<OIDC_TOKEN_FILE>",
"ram_role_arn":"<ROLE_ARN>",
"ram_session_name":"<ROLE_SESSION_NAME>",
"expired_seconds":3600
},
{
"name":"client4",
"mode":"ChainableRamRoleArn",
"source_profile":"<PROFILE_NAME>",
"ram_role_arn":"<ROLE_ARN>",
"ram_session_name":"<ROLE_SESSION_NAME>",
"expired_seconds":3600
}
]
}
In the config.json file, you can use mode to specify different credentials:
-
AK: Uses a user's AccessKey as the credential.
-
StsToken: Uses an STS Token as the credential.
-
RamRoleArn: Assumes a RAM role using its ARN to obtain the credential.
-
EcsRamRole: Uses the RAM role attached to an ECS instance to obtain the credential.
-
OIDC: Uses an OIDC ARN and an OIDC token to obtain the credential.
-
ChainableRamRoleArn: Uses a role chain. This mode specifies another profile in the JSON file to assume a new role and obtain a new credential.
The name parameter specifies the profile name. You can modify the other parameters as needed.
After the configuration is complete, the SDK initializes the credential client using the profile specified in the current field of the configuration file. You can also specify a profile name using the ALIBABA_CLOUD_PROFILE environment variable or by specifying the profile name in your code. For example, you can set the value of ALIBABA_CLOUD_PROFILE to client1.
Static credential provider
Static credentials are fixed access credentials, such as AccessKeys and STS Tokens, suitable for scenarios where credentials do not change.
This method is not recommended. An Alibaba Cloud account has full permissions on its resources, so a leaked AccessKey poses a significant security threat. Use the AccessKey of a RAM user that is granted only the minimum required permissions.
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
public class Demo {
private static final String ACCESS_KEY_ID = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
private static final String ACCESS_KEY_SECRET = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
private static final String SECURITY_TOKEN = System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN");
public static void main(String[] args) {
// Initialize the credential provider.
StaticCredentialProvider credentialProvider = StaticCredentialProvider.create(
Credential.builder()
.accessKeyId(ACCESS_KEY_ID)
.accessKeySecret(ACCESS_KEY_SECRET)
.securityToken(SECURITY_TOKEN)
.build()
);
// Omit the step of using credentialProvider to initialize AsyncClient...
}
}
RamRoleArn credential provider
This provider calls the AssumeRole operation of Security Token Service (STS) to obtain an STS Token.
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.RamRoleArnCredentialProvider;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
public class Demo {
public static void main(String[] args) {
// Initialize the credential provider.
StaticCredentialProvider staticCredentialProvider = StaticCredentialProvider.create(
Credential.builder()
.accessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
.accessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
.build()
);
RamRoleArnCredentialProvider credentialProvider = RamRoleArnCredentialProvider.builder()
// Another credential provider. This parameter is required.
.credentialsProvider(staticCredentialProvider)
// The ARN of the RAM role. This parameter is required. Example: acs:ram::123456789012****:role/adminrole
.roleArn("<RAM_ROLE_ARN>")
// A custom name for the role session. Set this to the identity of the user who calls the API. This parameter is optional.
.roleSessionName("<ROLE_SESSION_NAME>")
// The expiration time of the temporary credential in seconds. The default value is 3600. This parameter is optional.
.durationSeconds(3600)
// A more restrictive access policy. This parameter is optional. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
.policy("<POLICY>")
// The external ID of the role. This parameter is optional. It is used to prevent the confused deputy problem.
.externalId("<EXTERNAL_ID>")
// The STS Endpoint. The default value is sts.aliyuncs.com. This parameter is optional. If you set this value, the enableVpc and stsRegionId parameters do not take effect.
.stsEndpoint("sts.cn-hangzhou.aliyuncs.com")
// Specifies whether to enable the VPC Endpoint for STS. The default value is false. This parameter is optional.
.enableVpc(false)
// The region ID used to construct the STS Endpoint. This parameter is optional.
.stsRegionId("cn-hangzhou")
// The connection timeout for the AssumeRole call. The default value is 5000 milliseconds.
.connectionTimeout(5000)
// The read timeout for the AssumeRole call. The default value is 10000 milliseconds.
.readTimeout(10000)
.build();
// Omit the step of using credentialProvider to initialize AsyncClient...
}
}
EcsRamRole credential provider
ECS and ECI instances support attaching instance RAM roles. Applications running on these instances can use the Credentials tool to automatically obtain the STS Token for the attached role.
By default, the Credentials tool uses secure mode (IMDSv2) to access the ECS instance metadata service (IMDS) and falls back to normal mode on failure. You can set the disableIMDSv1 parameter or the ALIBABA_CLOUD_IMDSV1_DISABLED environment variable to control fallback behavior:
-
If the value is false (default), the tool attempts to obtain the access credential in normal mode.
-
If the value is true, the tool attempts to obtain the access credential only in secure mode and throws an exception upon failure.
Whether the server supports IMDSv2 depends on your server configuration.
You can also set the ALIBABA_CLOUD_ECS_METADATA_DISABLED=true environment variable to disable credential access from ECS metadata.
-
For more information about ECS instance metadata, see Instance metadata.
-
For information about how to grant a RAM role to an ECS or ECI instance, see Create a RAM role and grant it to an ECS instance and Grant an instance RAM role to an ECI instance.
import com.aliyun.auth.credentials.provider.EcsRamRoleCredentialProvider;
public class Demo {
public static void main(String[] args) {
// Method 1
EcsRamRoleCredentialProvider credentialProvider = EcsRamRoleCredentialProvider.builder()
// The name of the RAM role granted to the ECS instance. This parameter is optional. If not specified, the role name is retrieved automatically. Specify the role name to reduce the number of requests. You can also set the role name using the ALIBABA_CLOUD_ECS_METADATA environment variable.
.roleName("<ROLE_NAME>")
// A value of true forces the use of secure mode. Default value: false. The system first tries to get credentials in secure mode. If it fails, it switches to normal mode (IMDSv1).
.disableIMDSv1(false)
// The HTTP client connection timeout in milliseconds. This parameter is optional. Default value: 1000.
.connectionTimeout(1000)
// The HTTP client read timeout in milliseconds. This parameter is optional. Default value: 1000.
.readTimeout(1000)
.build();
// Method 2:
// EcsRamRoleCredentialProvider credentialProvider = EcsRamRoleCredentialProvider.create("<ROLE_NAME>");
// Omit the step of using credentialProvider to initialize AsyncClient...
}
}
OIDCRoleArn credential provider
If you use OIDC for authentication and have created a RAM role for an OIDC identity provider, you can provide the OIDC provider ARN, OIDC token file path, and RAM role ARN to the Credentials tool. The tool then automatically calls the AssumeRoleWithOIDC API to obtain an STS token for the RAM role, which is used as the access credential. Credentials obtained this way support automatic refresh. For more information, see Automatic refresh of session credentials. For example, if your application runs in a Container Service for Kubernetes (ACK) cluster with RRSA enabled, the Credentials tool can read the OIDC configuration from the pod's environment variables and call the AssumeRoleWithOIDC API to obtain an STS token. You can then use this STS token to access Alibaba Cloud services.
import com.aliyun.auth.credentials.provider.OIDCRoleArnCredentialProvider;
public class Demo {
public static void main(String[] args) {
OIDCRoleArnCredentialProvider credentialProvider = OIDCRoleArnCredentialProvider.builder()
// The OIDC provider ARN. You can set this using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
.oidcProviderArn("<OIDC_PROVIDER_ARN>")
// The path to the OIDC token file. You can set this using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
.oidcTokenFilePath("<OIDC_TOKEN_FILE_PATH>")
// The ARN of the RAM role. This parameter is required. Example: acs:ram::123456789012****:role/adminrole
.roleArn("<RAM_ROLE_ARN>")
// A custom name for the role session. Set this to the identity of the user who calls the API. This parameter is optional.
.roleSessionName("<ROLE_SESSION_NAME>")
// The expiration time of the temporary credential in seconds. The default value is 3600. This parameter is optional.
.durationSeconds(3600)
// A more restrictive access policy. This parameter is optional. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
.policy("<POLICY>")
// The STS Endpoint. The default value is sts.aliyuncs.com. This parameter is optional. If you set this value, the enableVpc and stsRegionId parameters do not take effect.
.stsEndpoint("sts.cn-hangzhou.aliyuncs.com")
// Specifies whether to enable the VPC Endpoint for STS. The default value is false. This parameter is optional.
.enableVpc(false)
// The region ID used to construct the STS Endpoint. This parameter is optional.
.stsRegionId("cn-hangzhou")
// The connection timeout for the AssumeRoleWithOIDC call. The default value is 10000 milliseconds.
.readTimeout(10000)
// The read timeout for the AssumeRoleWithOIDC call. The default value is 5000 milliseconds.
.connectionTimeout(5000)
.build();
// Omit the step of using credentialProvider to initialize AsyncClient...
}
}
URL credential provider
You can encapsulate the Security Token Service (STS) behind a service URI, allowing external services to obtain an STS token without exposing sensitive information like AKs. The Credentials tool can then use this URI to fetch an STS token to use as the access credential. Credentials obtained this way support automatic refresh. For more information, see Automatic refresh of session credentials.
The URI must meet the following conditions:
-
Supports GET requests.
-
Returns an HTTP 2xx status code.
-
The response body must return a JSON object with the following structure:
{ "Code": "Success", "AccessKeySecret": "yourAccessKeySecret", "AccessKeyId": "STS.****************", "Expiration": "2021-09-26T03:46:38Z", "SecurityToken": "yourSecurityToken" }
import com.aliyun.auth.credentials.provider.URLCredentialProvider;
public class Demo {
public static void main(String[] args) {
URLCredentialProvider credentialProvider = URLCredentialProvider.builder()
// The credential URI, in the format http://local_or_remote_uri/. You can set this using the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
.credentialsURI("http://localhost:8080/api/ecs/send")
// The HTTP request connection timeout in milliseconds. The default value is 5000. This parameter is optional.
.connectionTimeout(5000)
// The HTTP request read timeout in milliseconds. The default value is 10000. This parameter is optional.
.readTimeout(1000)
.build();
// Omit the step of using credentialProvider to initialize AsyncClient...
}
}
The address must meet the following requirements:
-
This operation supports GET requests.
-
The response status code is 2xx.
-
The response body has the following structure:
{ "AccessKeyId": "AccessKeyId", "AccessKeySecret": "AccessKeySecret", "Code": "Success", "Expiration": "2025-07-04T15:06:21Z", "SecurityToken": "SecurityToken" }
Default credential chain
The default credential chain searches for credentials in a predefined order. If no credential is found after all sources are checked, an exception is thrown. The search order is as follows:
1. System properties
The Credentials tool first attempts to retrieve credentials from system properties.
-
If alibabacloud.accessKeyId and alibabacloud.accessKeySecret are defined in the system properties, an AccessKey is used as the default credential.
-
If alibabacloud.accessKeyId, alibabacloud.accessKeySecret, and alibabacloud.sessionToken are defined in the system properties, an STS Token is used as the default credential.
You can add the following JVM parameters when you run the Java program to specify these values:
-Dalibabacloud.accessKeyId=your-access-key-id -Dalibabacloud.accessKeySecret=your-access-key-secret
2. Environment variables
If no credential is found in the system properties, the provider chain then checks for environment variables.
-
If both ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are present and not empty, the provider chain uses them as the default credential.
-
If ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and ALIBABA_CLOUD_SECURITY_TOKEN are also set, the provider chain uses an STS token as the default credential.
3. OIDC RAM role
If no credential has been found, the provider chain checks for the following environment variables related to an OIDC RAM role:
-
ALIBABA_CLOUD_ROLE_ARN: The ARN of the RAM role.
-
ALIBABA_CLOUD_OIDC_PROVIDER_ARN: The ARN of the OIDC provider.
-
ALIBABA_CLOUD_OIDC_TOKEN_FILE: The file path of the OIDC token.
If all three environment variables are present and not empty, the provider chain uses these values to call the AssumeRoleWithOIDC API of the Security Token Service (STS) to obtain an STS token.
4. Configuration file
If no credential has been found, the provider chain attempts to load the shared credentials file, config.json, from its default location and uses the credential specified in the file.
-
Linux/macOS:
~/.aliyun/config.json -
Windows:
C:\Users\USER_NAME\.aliyun\config.json
To configure a credential this way, you can use the Alibaba Cloud CLI or manually create a config.json file in the appropriate path. The following example shows the content format:
{
"current": "<PROFILE_NAME>",
"profiles": [
{
"name": "<PROFILE_NAME>",
"mode": "AK",
"access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
"access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>"
},
{
"name": "<PROFILE_NAME1>",
"mode": "StsToken",
"access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
"access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
"sts_token": "<SECURITY_TOKEN>"
},
{
"name":"<PROFILE_NAME2>",
"mode":"RamRoleArn",
"access_key_id":"<ALIBABA_CLOUD_ACCESS_KEY_ID>",
"access_key_secret":"<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
"ram_role_arn":"<ROLE_ARN>",
"ram_session_name":"<ROLE_SESSION_NAME>",
"expired_seconds":3600
},
{
"name":"<PROFILE_NAME3>",
"mode":"EcsRamRole",
"ram_role_name":"<RAM_ROLE_ARN>"
},
{
"name":"<PROFILE_NAME4>",
"mode":"OIDC",
"oidc_provider_arn":"<OIDC_PROVIDER_ARN>",
"oidc_token_file":"<OIDC_TOKEN_FILE>",
"ram_role_arn":"<ROLE_ARN>",
"ram_session_name":"<ROLE_SESSION_NAME>",
"expired_seconds":3600
},
{
"name":"<PROFILE_NAME5>",
"mode":"ChainableRamRoleArn",
"source_profile":"<PROFILE_NAME>",
"ram_role_arn":"<ROLE_ARN>",
"ram_session_name":"<ROLE_SESSION_NAME>",
"expired_seconds":3600
}
]
}
|
Parameter |
Description |
|
current |
Specify the credential name to retrieve the corresponding credential configuration. The credential name is the value of the |
|
profiles |
Contains a collection of credential configurations. The
|
5. ECS instance RAM role
If no higher-priority credential is found, the Credentials tool retrieves a credential from the RAM role attached to the ECS instance. By default, the tool uses secure mode (IMDSv2) to access the ECS instance metadata service (IMDS) and obtain the STS Token for the instance RAM role. The tool automatically retrieves the RoleName and then the credential, which involves two requests. To reduce this to a single request, set the ALIBABA_CLOUD_ECS_METADATA environment variable to the instance RAM role name. If secure mode fails, the tool falls back to normal mode. You can set the ALIBABA_CLOUD_IMDSV1_DISABLE environment variable to control fallback behavior:
-
If the value is false, the tool attempts to obtain the access credential in normal mode.
-
If the value is true, the tool attempts to obtain the access credential only in secure mode and throws an exception upon failure.
Whether the server supports IMDSv2 depends on your server configuration.
You can also set the ALIBABA_CLOUD_ECS_METADATA_DISABLED=true environment variable to disable credential access from ECS metadata.
-
For more information about ECS instance metadata, see Instance metadata.
-
For information about how to grant a RAM role to an ECS or ECI instance, see Create a RAM role and grant it to an ECS instance and Grant an instance RAM role to an ECI instance.
6. Credentials tool URI
If no credential has been found, the provider chain checks for the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. If this variable is set and points to a valid URI, the chain accesses the URI to retrieve an STS token.