Manage access credentials
The Alibaba Cloud SDK for Java V1.0 requires a valid access credential to call OpenAPI operations. The SDK supports multiple credential methods for secure development.
Prerequisites
The version of the aliyun-java-sdk-core package must be 4.7.3 or later.
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.7.3</version>
</dependency>
Method 1: AccessKey
-
A leaked Alibaba Cloud account AccessKey compromises all resources under the account. Use the AccessKey of a Resource Access Management (RAM) user instead. Create an AccessKey.
-
Set the
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRETenvironment variables in your runtime environment. Configure environment variables on Linux, macOS, and Windows.
-
Initialize the client by configuring an AccessKey using DefaultProfile.
import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.profile.DefaultProfile; public class Sample { public static void main(String[] args) { DefaultProfile profile = DefaultProfile.getProfile( "<REGION_ID>", // Retrieve the AccessKey ID of the RAM user from an environment variable. System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), // Retrieve the AccessKey secret of the RAM user from an environment variable. System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); IAcsClient client = new DefaultAcsClient(profile); // The API call logic is omitted. } } -
Initialize the client by configuring an AccessKey using BasicCredentials.
import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.auth.BasicCredentials; import com.aliyuncs.profile.DefaultProfile; public class Sample { public static void main(String[] args) { BasicCredentials basicCredentials = new BasicCredentials( // Retrieve the AccessKey ID of the RAM user from an environment variable. System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), // Retrieve the AccessKey secret of the RAM user from an environment variable. System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") ); DefaultProfile profile = DefaultProfile.getProfile("<REGION_ID>"); IAcsClient client = new DefaultAcsClient(profile, basicCredentials); // The API call logic is omitted. } }
Method 2: STS token
Initialize the client with a temporary access credential (STS token).
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.profile.DefaultProfile;
public class Test {
public static void main(String[] args) {
DefaultProfile profile = DefaultProfile.getProfile(
"<REGION_ID>",
// Retrieve the AccessKey ID of the RAM user from an environment variable.
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// Retrieve the AccessKey secret of the RAM user from an environment variable.
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
// The STS token.
System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN"));
IAcsClient client = new DefaultAcsClient(profile);
// The API call logic is omitted.
}
}
Method 3: RAM role ARN
Call the AssumeRole operation of Security Token Service (STS) to get an STS token.
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.STSAssumeRoleSessionCredentialsProvider;
import com.aliyuncs.profile.DefaultProfile;
public class Sample {
public static void main(String[] args) {
DefaultProfile profile = DefaultProfile.getProfile("<REGION_ID>");
// Use a RAM role ARN.
STSAssumeRoleSessionCredentialsProvider stsProvider = STSAssumeRoleSessionCredentialsProvider
.builder()
// Required. Retrieve the AccessKey ID of the RAM user from an environment variable.
.accessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Retrieve the AccessKey secret of the RAM user from an environment variable.
.accessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
// The Alibaba Cloud Resource Name (ARN) of the RAM role. Required unless the ALIBABA_CLOUD_ROLE_ARN environment variable is set.
.roleArn("<ROLE_ARN>")
// A custom session name. Optional. Can also be set by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
.roleSessionName("<ROLE_SESSION_NAME>")
// A custom policy. Optional. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
.policy("<POLICY>")
// An external ID to prevent the confused deputy problem. Optional.
.externalId("<<EXTERNAL_ID>>")
// The duration of the access credential in seconds. Optional. Defaults to 3600 and must not exceed 43200 (12 hours).
.durationSeconds(3600)
// The region ID for the AssumeRole API call. Optional.
.stsRegionId("<STS_REGION_ID>")
.build();
DefaultAcsClient client = new DefaultAcsClient(profile, stsProvider);
// The API call logic is omitted.
}
}
Method 4: Instance RAM role
The SDK can retrieve credentials from an instance RAM role attached to an Elastic Compute Service (ECS) or Elastic Container Instance (ECI) instance, eliminating the need for static AccessKeys. The SDK automatically detects the attached RAM role and obtains an STS token from the metadata server.
The Credentials tool uses IMDSv2 (security hardening mode) by default. If IMDSv2 fails, the disableIMDSv1 setting controls fallback behavior:
-
false(default): falls back to normal mode (IMDSv1) to retrieve credentials. -
true: throws an exception instead of falling back to IMDSv1.
IMDSv2 support depends on your instance configuration.
Ensure that the ECS instance is configured with a RAM role.
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.InstanceProfileCredentialsProvider;
import com.aliyuncs.profile.DefaultProfile;
public class Sample {
public static void main(String[] args) {
DefaultProfile profile = DefaultProfile.getProfile("<REGION_ID>");
// Use an instance RAM role.
InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider
.builder()
// The name of the RAM role attached to the instance.
.roleName("<ROLE_NAME>")
//.disableIMDSv1(false)
.build();
DefaultAcsClient client = new DefaultAcsClient(profile, provider);
// The API call logic is omitted.
}
}
Method 5: OIDC RAM role
In Container Service for Kubernetes (ACK), the RAM Roles for Service Accounts (RRSA) feature associates RAM roles with individual pods. Each application assumes a different RAM role and uses temporary credentials to access Alibaba Cloud resources, eliminating long-term AccessKeys.
ACK mounts an OIDC token file for each pod and injects configuration as environment variables. The SDK calls the AssumeRoleWithOIDC operation of STS to exchange the OIDC token for an STS token. Isolate pod permissions by using RRSA.
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.auth.OIDCCredentialsProvider;
import com.aliyuncs.profile.DefaultProfile;
public class Sample {
public static void main(String[] args) {
// Use an OIDC-based RAM role.
OIDCCredentialsProvider provider = OIDCCredentialsProvider
.builder()
// The ARN of the OIDC provider. Required unless the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable is set.
.oidcProviderArn(System.getenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN"))
// The path of the OIDC token file. Required unless the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable is set.
.oidcTokenFilePath(System.getenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE"))
// The ARN of the RAM role. Required unless the ALIBABA_CLOUD_ROLE_ARN environment variable is set.
.roleArn(System.getenv("ALIBABA_CLOUD_ROLE_ARN"))
// A custom session name. Optional.
.roleSessionName("<ROLE_SESSION_NAME>")
// A custom policy. Optional. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
.policy("<POLICY>")
// The duration of the access credential in seconds. Optional. Defaults to 3600 and must not exceed 43200 (12 hours).
.durationSeconds(3600)
// The region ID of STS. Optional.
.stsRegionId("<REGION_ID>")
.build();
DefaultProfile profile = DefaultProfile.getProfile(
// Specify the region ID of the client.
"<REGION_ID>");
IAcsClient client = new DefaultAcsClient(profile, provider);
// The API call logic is omitted.
}
}
Method 6: Bearer token
This method is supported only by Cloud Call Center (CCC).
import com.aliyuncs.auth.BearerTokenCredentials;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.DefaultAcsClient;
public class BearerToken {
public static void main(String[] args) {
DefaultProfile profile = DefaultProfile.getProfile("<REGION_ID>");
// Set the access credential by using BearerTokenCredentials.
BearerTokenCredentials bearerTokenCredential = new BearerTokenCredentials("<BEARER_TOKEN>");
DefaultAcsClient client = new DefaultAcsClient(profile, bearerTokenCredential);
// The API call logic is omitted.
}
}
Method 7: Default credential provider chain
If no credential is explicitly provided, the SDK uses the default credential provider chain.
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
public class Test {
public static void main(String[] args) throws ClientException {
// Use the default credential provider chain.
IAcsClient client = new DefaultAcsClient("<REGION_ID>");
// The API call logic is omitted.
}
}
The default credential provider chain searches for available credentials in the following order:
1. System properties
If the alibabacloud.accessKeyId and alibabacloud.accessKeyIdSecret system properties are defined and not empty, the SDK uses them to create default credentials.
2. Environment variables
If the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are defined and not empty, the SDK uses them as default credentials.
3. OIDC RAM role
The SDK checks for these environment variables:
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 path of the OIDC token file.
If all three environment variables are set, the SDK calls the AssumeRoleWithOIDC operation of STS to obtain an STS token, which is then used as the default credential.
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
The SDK checks for the ALIBABA_CLOUD_ECS_METADATA environment variable, which specifies an instance RAM role name. If set, the SDK retrieves an STS token from the ECS metadata server.
6. Credentials URI
The SDK checks for the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. If set, the SDK requests a temporary credential from the specified URI.