All Products
Search
Document Center

Alibaba Cloud SDK:Manage access credentials

Last Updated:Jun 18, 2025

When you use Alibaba Cloud SDK to call OpenAPI operations for resource management, correctly configuring credential information is crucial. Alibaba Cloud Credentials for Java provides a comprehensive set of convenient features that support various credential types, including default credentials, AccessKey pairs, and Security Token Service (STS) tokens, to help you efficiently obtain and manage access credentials. This topic describes how to configure different types of credentials and how to use default credentials based on priority. After reading this topic, you will have a thorough understanding of how to configure and maintain credentials in Alibaba Cloud SDK to ensure efficient and highly secure operations on cloud resources.

Background information

A credential is a set of information used to prove the identity of a user. When you log on to the system, you must use a valid credential to complete identity authentication. The following types of credentials are commonly used:

  1. The AccessKey pair of an Alibaba Cloud account or a Resource Access Management (RAM) user. An AccessKey pair is permanently valid and consists of an AccessKey ID and an AccessKey secret.

  2. An STS token of a RAM role. An STS token is a temporary credential with a customizable validity period and permissions. For more information, see What is STS.

  3. A bearer token. It is used for identity authentication and authorization.

Prerequisites

Install the Credentials tool

You can use Maven to install the Credentials tool:

<dependency>
   <groupId>com.aliyun</groupId>
   <artifactId>credentials-java</artifactId>
   <version>last-version</version>
</dependency>
  • Use the latest version of the Credentials dependency package to ensure support for all credentials. For information about all released versions, see ChangeLog.txt.

  • We recommend that you use Alibaba Cloud SDK V2.0. If you do not use Alibaba Cloud SDK V2.0 but rely on the credentials-java module, you must add the following dependency. Otherwise, an error is reported indicating that the com.aliyun.tea.TeaModel class file does not exist.

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>tea</artifactId>
      <version>last-version</version>
    </dependency>
    Note

    For information about the version of the tea package, see tea-java.

Parameter description for the Credentials tool

The configuration parameters of the Credentials tool are defined in com.aliyun.credentials.models.Config. The credential type is specified by the required parameter type. After you determine the credential type, you must select the corresponding parameters based on the credential type. The following table describes the valid values of type and the parameters that are supported by each credential type. In the table, indicates a required parameter, - indicates an optional parameter, and × indicates an unsupported parameter.

Note

The credential types and parameters that are not listed in the following table are not recommended for use.

type

access_key

sts

ram_role_arn

ecs_ram_role

oidc_role_arn

credentials_uri

bearer

accessKeyId: the ID of the access credential.

×

×

×

×

accessKeySecret: the secret of the access credential.

×

×

×

×

securityToken: the STS token.

×

-

×

×

×

×

roleArn: the Alibaba Cloud Resource Name (ARN) of the RAM role.

×

×

×

×

×

roleSessionName: the custom session name. Default format: credentials-java-current timestamp.

×

×

-

×

-

×

×

roleName: the name of the RAM role.

×

×

×

-

×

×

×

disableIMDSv1: specifies whether to forcibly use the security hardening mode. Default value: false.

×

×

×

-

×

×

×

bearerToken: the bearer token.

×

×

×

×

×

×

policy: the custom permission policy.

×

×

-

×

-

×

×

roleSessionExpiration: the validity period of the session. Default value: 3600 seconds.

×

×

-

×

-

×

×

oidcProviderArn: the ARN of the OIDC IdP.

×

×

×

×

×

×

oidcTokenFilePath: the path of the OIDC token file.

×

×

×

×

×

×

externalId: the external ID of the role. This parameter is used to prevent the confused deputy problem. For more information, see Use ExternalId to prevent the confused deputy problem.

×

×

-

×

×

×

×

credentialsURI: the URI of the credential.

×

×

×

×

×

×

STSEndpoint: the endpoint of STS. Both VPC endpoints and public endpoints are supported. For information about the valid values, see Service registration. Default value: sts.aliyuncs.com.

×

×

-

×

-

×

×

timeout: the read timeout period of an HTTP request. Default value: 5000 milliseconds.

×

×

-

-

-

-

×

connectTimeout: the connection timeout period of an HTTP request. Default value: 10000 milliseconds.

×

×

-

-

-

-

×

Initialize a Credentials client

You can use one of the following methods to initialize a Credentials client based on your business requirements:

Important
  • If you use a plaintext AccessKey pair in a project, the AccessKey pair may be leaked due to improper permission management on the code repository. This may threaten the security of all resources within the account to which the AccessKey pair belongs. We recommend that you store the AccessKey pair in environment variables or configuration files.

  • We recommend that you use the singleton pattern when you initialize a Credentials client. This not only enables the credential caching feature of the SDK but also prevents traffic throttling issues and resource waste caused by multiple API calls. For more information, see Auto-refresh mechanism for session credentials.

Method 1: Use the default credential provider chain

If you do not specify a method to initialize a Credentials client, the default credential provider chain is used. For more information about the logic of reading default credentials, see Default credential provider chain.

import com.aliyun.credentials.Client;

public class DemoTest {
    public static void main(String[] args) throws Exception{
        // No parameters specified
        Client credentialClient = new Client();
        // Content for initializing cloud product client using credential client is omitted...
    }
}

Call example

The following example shows how to call the DescribeRegions operation of Elastic Compute Service (ECS). You must first install ECS SDK.

import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.DescribeRegionsRequest;
import com.aliyun.ecs20140526.models.DescribeRegionsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

public class Sample {
    public static void main(String[] args) throws Exception {
        // Use the default credential to initialize a Credentials client.
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();

        // Use the Credentials client to initialize the ECS SDK client.
        Config ecsConfig = new Config();
        ecsConfig.setCredential(credentialClient);
        ecsConfig.setEndpoint("ecs.aliyuncs.com");
        Client ecsClient = new Client(ecsConfig);
        // Initialize the request to call the DescribeRegions operation.
        DescribeRegionsRequest describeInstancesRequest = new DescribeRegionsRequest();
        // Initialize the runtime configuration.
        RuntimeOptions runtime = new RuntimeOptions();
        // Call the DescribeRegions operation and obtain a response.
        DescribeRegionsResponse response = ecsClient.describeRegionsWithOptions(describeInstancesRequest, runtime);
        System.out.println(response.body.toMap());
    }
}

Method 2: Use an AccessKey pair

This method initializes a Credentials client by using an AccessKey pair. For information about how to obtain an AccessKey pair, see Create an AccessKey pair.

Warning

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 an AccessKey pair of a RAM user that is granted permissions based on the principle of least privilege (PoLP) to initialize a Credentials client.

import com.aliyun.credentials.Client;
import com.aliyun.credentials.models.Config;

public class DemoTest {
    public static void main(String[] args) throws Exception{
        Config credentialConfig = new Config();
        credentialConfig.setType("access_key");
        credentialConfig.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
        credentialConfig.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        Client credentialClient = new Client(credentialConfig);
        // No value is specified for new Client().
    }
}

Call example

The following example shows how to call the DescribeRegions operation of ECS. You must first install ECS SDK.

import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.DescribeRegionsRequest;
import com.aliyun.ecs20140526.models.DescribeRegionsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

public class Sample {
    public static void main(String[] args) throws Exception {
        // Use an AccessKey pair to initialize a Credentials client.
        com.aliyun.credentials.models.Config credentialsConfig = new com.aliyun.credentials.models.Config();
        // Specify the type of the credential.
        credentialsConfig.setType("access_key");
        // Specify the AccessKey ID.
        credentialsConfig.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
        // Specify the AccessKey secret.
        credentialsConfig.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client(credentialsConfig);

        // Use the Credentials client to initialize the ECS SDK client.
        Config ecsConfig = new Config();
        ecsConfig.setCredential(credentialClient);
        ecsConfig.setEndpoint("ecs.aliyuncs.com");
        Client ecsClient = new Client(ecsConfig);
        // Initialize a request to call the DescribeRegions operation.
        DescribeRegionsRequest describeInstancesRequest = new DescribeRegionsRequest();
        // Initialize the runtime configuration.
        RuntimeOptions runtime = new RuntimeOptions();
        // Call the DescribeRegions operation and obtain a response.
        DescribeRegionsResponse response = ecsClient.describeRegionsWithOptions(describeInstancesRequest, runtime);
        System.out.println(response.body.toMap());
    }
}

Method 3: Use an STS token

This method initializes a Credentials client by using a static STS token. For information about how to obtain an STS token, see What is STS. The following example shows how to initialize a Credentials client by using an STS token. The example does not show how to obtain an STS token.

import com.aliyun.credentials.Client;
import com.aliyun.credentials.models.Config;

public class DemoTest {
    public static void main(String[] args) {
        Config credentialConfig = new Config();
        credentialConfig.setType("sts");
        // Obtain the AccessKey ID from the environment variable.
        credentialConfig.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
        // Obtain the AccessKey secret from the environment variable.
        credentialConfig.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Obtain the temporary STS token from the environment variable.
        credentialConfig.setSecurityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN"));
        Client credentialClient = new Client(credentialConfig);
        // No value is specified for new Client().
    }
}

Call example

The following example shows how to call the DescribeRegions operation of ECS. You must first install Elastic Compute Service SDK and Security Token Service SDK.

import com.aliyun.ecs20140526.models.DescribeRegionsRequest;
import com.aliyun.ecs20140526.models.DescribeRegionsResponse;
import com.aliyun.sts20150401.Client;
import com.aliyun.sts20150401.models.AssumeRoleRequest;
import com.aliyun.sts20150401.models.AssumeRoleResponse;
import com.aliyun.sts20150401.models.AssumeRoleResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

public class Sample {
    public static void main(String[] args) throws Exception {
        // Create an StsClient object and call the AssumeRole operation to obtain an STS token
        Config config = new Config()
                // Obtain the AccessKey ID from the environment variable
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Obtain the AccessKey secret from the environment variable
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        config.endpoint = "sts.cn-hangzhou.aliyuncs.com";
        Client client = new Client(config);
        AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest()
                // Specify the ARN of the RAM role to be assumed. Example: acs:ram::123456789012****:role/adminrole. You can obtain the value from the ALIBABA_CLOUD_ROLE_ARN environment variable.
                .setRoleArn("<RoleArn>")
                // Specify the role session name. You can obtain the value from the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
                .setRoleSessionName("<RoleSessionName>");
        RuntimeOptions runtime = new RuntimeOptions();
        AssumeRoleResponse assumeRoleResponse = client.assumeRoleWithOptions(assumeRoleRequest, runtime);
        AssumeRoleResponseBody.AssumeRoleResponseBodyCredentials assumeRoleResponseBodyCredentials = assumeRoleResponse.body.credentials;

        // Use an STS token to initialize a Credentials client.
        com.aliyun.credentials.models.Config credentialsConfig = new com.aliyun.credentials.models.Config();
        credentialsConfig.setType("sts"); // Specify the type of the credential.
        credentialsConfig.setAccessKeyId(assumeRoleResponseBodyCredentials.accessKeyId);
        credentialsConfig.setAccessKeySecret(assumeRoleResponseBodyCredentials.accessKeySecret);
        credentialsConfig.setSecurityToken(assumeRoleResponseBodyCredentials.securityToken);
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client(credentialsConfig);

        // Initialize the request to call the DescribeRegions operation.
        Config ecsConfig = new Config();
        ecsConfig.setEndpoint("ecs.aliyuncs.com");
        ecsConfig.setCredential(credentialClient);
        com.aliyun.ecs20140526.Client ecsClient = new com.aliyun.ecs20140526.Client(ecsConfig);
        DescribeRegionsRequest describeInstancesRequest = new DescribeRegionsRequest();
        RuntimeOptions describeRegionsRuntime = new RuntimeOptions();

        // Call the DescribeRegions operation and obtain a response.
        DescribeRegionsResponse response = ecsClient.describeRegionsWithOptions(describeInstancesRequest, describeRegionsRuntime);
        System.out.println(response.body.toMap());
    }
}

Method 4: Use an AccessKey pair and a RAM role

The underlying logic of this method is to use an STS token. The Credentials tool can call the AssumeRole operation to obtain an STS token by specifying the ARN of a RAM role.

import com.aliyun.credentials.Client;
import com.aliyun.credentials.models.Config;

public class DemoTest {
  public static void main(String[] args) throws Exception {
    Config credentialConfig = new Config();
    credentialConfig.setType("ram_role_arn");
    credentialConfig.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
    credentialConfig.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
    // Specify the ARN of the RAM role to be assumed. Example: acs:ram::123456789012****:role/adminrole. You can obtain the value from the ALIBABA_CLOUD_ROLE_ARN environment variable.
    credentialConfig.setRoleArn("<RoleArn>");
    // Specify the role session name. You can obtain the value from the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
    credentialConfig.setRoleSessionName("<RoleSessionName>");
    // Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    credentialConfig.setPolicy("<Policy>");
    // Optional. Specify the external ID of the RAM role. This parameter is used to prevent the confused deputy problem.
    credentialConfig.setExternalId("<ExternalId>");
    credentialConfig.setRoleSessionExpiration(3600);
    Client credentialClient = new Client(credentialConfig);
    // No value is specified for new Client().
  }
}

Call example

The following example shows how to call the DescribeRegions operation of ECS. You must first install ECS SDK.

import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.DescribeRegionsRequest;
import com.aliyun.ecs20140526.models.DescribeRegionsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

public class Sample {
    public static void main(String[] args) throws Exception {
        // Use an AccessKey pair and a RAM role to initialize a Credentials client
        com.aliyun.credentials.models.Config credentialsConfig = new com.aliyun.credentials.models.Config();
        // The credential type
        credentialsConfig.setType("ram_role_arn");
        // Obtain the AccessKey ID from the environment variable
        credentialsConfig.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
        // Obtain the AccessKey secret from the environment variable
        credentialsConfig.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Specify the ARN of the RAM role to be assumed. Example: acs:ram::123456789012****:role/adminrole. You can obtain the value from the ALIBABA_CLOUD_ROLE_ARN environment variable.
        credentialsConfig.setRoleArn("<RoleArn>");
        // Specify the role session name. You can obtain the value from the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
        credentialsConfig.setRoleSessionName("<RoleSessionName>");
        // Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
        credentialsConfig.setPolicy("<Policy>");
        // Not required, the external ID of the RAM role
        // This parameter is provided by an external party and is used to prevent the confused deputy problem.
        credentialsConfig.setExternalId("<ExternalId>");
        // Specify the validity period of the session.
        credentialsConfig.setRoleSessionExpiration(3600);
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client(credentialsConfig);

        // Use the Credentials client to initialize the ECS SDK client.
        Config ecsConfig = new Config();
        ecsConfig.setEndpoint("ecs.aliyuncs.com");
        ecsConfig.setCredential(credentialClient);
        Client ecsClient = new Client(ecsConfig);
        DescribeRegionsRequest describeInstancesRequest = new DescribeRegionsRequest();
        RuntimeOptions runtime = new RuntimeOptions();
        // Call the DescribeRegions operation and obtain a response.
        DescribeRegionsResponse response = ecsClient.describeRegionsWithOptions(describeInstancesRequest, runtime);
        System.out.println(response.body.toMap());
    }
}

Method 5: Obtain the credential information by using the RAM role of an ECS instance

ECS instances and elastic container instances can be assigned RAM roles. Programs that run on the instances can use the Credentials tool to automatically obtain an STS token for the RAM role. The STS token can be used to initialize the Credentials client.

By default, the Credentials tool accesses the metadata server of ECS in security hardening mode (IMDSv2). If an exception occurs in the security hardening mode, the Credentials tool obtains the access credential in normal mode. You can also set the disableIMDSv1 parameter or the ALIBABA_CLOUD_IMDSV1_DISABLED environment variable to specify how to handle exceptions:

  • false (default): The Credentials tool continues to obtain the access credential in normal mode (IMDSv1).

  • true: The exception is thrown and the Credentials tool continues to obtain the access credential in security hardening mode (IMDSv2).

The configurations for the metadata server determine whether the server supports the security hardening mode.

You can also configure the ALIBABA_CLOUD_ECS_METADATA_DISABLED=true environment variable to disable access to ECS instance metadata.

Note
Note

If you obtain an STS token in security hardening mode (IMDSv2), make sure that the version of credentials-java is 0.3.10 or later.

import com.aliyun.credentials.Client;
import com.aliyun.credentials.models.Config;

public class DemoTest {
    public static void main(String[] args) throws Exception {
        Config credentialConfig = new Config();
        credentialConfig.setType("ecs_ram_role");
        // Optional. Specify the name of the RAM role of the ECS instance. If you do not specify this parameter, its value is automatically obtained. To reduce the number of requests, we recommend that you specify this parameter. You can obtain the value from the the ALIBABA_CLOUD_ECS_METADATA environment variable.
        credentialConfig.setRoleName("<RoleName>");
        // A value of true specifies that the security hardening mode is forcibly used. The default value is false, which specifies that the system first tries to obtain the access credential in security hardening mode. If the access credential fails to be obtained, the normal mode is used.
        credentialConfig.setDisableIMDSv1(false);
        Client credentialClient = new Client(credentialConfig);
        // No value is specified for new Client().
    }
}

Call example

The following example shows how to call the DescribeRegions operation of ECS. You must first install ECS SDK.

import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.DescribeRegionsRequest;
import com.aliyun.ecs20140526.models.DescribeRegionsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

public class Sample {
    public static void main(String[] args) throws Exception {
        // Use the RAM role of an ECS instance to initialize a Credentials client.
        com.aliyun.credentials.models.Config credentialsConfig = new com.aliyun.credentials.models.Config();
        // Specify the type of the credential.
        credentialsConfig.setType("ecs_ram_role");
        // Optional. Specify the name of the RAM role of the ECS instance. If you do not specify this parameter, its value is automatically obtained. To reduce the number of requests, we recommend that you specify this parameter. You can obtain the value from the the ALIBABA_CLOUD_ECS_METADATA environment variable.
        credentialsConfig.setRoleName("<RoleName>");
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client(credentialsConfig);

        // Use the Credentials client to initialize the ECS SDK client.
        Config ecsConfig = new Config();
        ecsConfig.setCredential(credentialClient);
        ecsConfig.setEndpoint("ecs.aliyuncs.com");
        Client ecsClient = new Client(ecsConfig);
        // Initialize a request to call the DescribeRegions operation.
        DescribeRegionsRequest describeInstancesRequest = new DescribeRegionsRequest();
        // Initialize the runtime configuration.
        RuntimeOptions runtime = new RuntimeOptions();
        // Call the DescribeRegions operation and obtain a response.
        DescribeRegionsResponse response = ecsClient.describeRegionsWithOptions(describeInstancesRequest, runtime);
        System.out.println(response.body.toMap());
    }
}

Method 6: Use the RAM role of an OIDC IdP

To ensure the security of cloud resources and allow untrusted applications to securely obtain the required STS tokens to implement application-level permission minimization, you can use RAM Roles for Service Account (RRSA). Alibaba Cloud container clusters create and mount the corresponding service account OIDC token files for different application pods and inject the relevant configuration information into environment variables. The Credentials tool obtains the configuration information from the environment variables and calls the AssumeRoleWithOIDC operation of STS to exchange for the STS token of the bound role.

The following environment variables are injected into the pod:

ALIBABA_CLOUD_ROLE_ARN: the ARN of the RAM role.

ALIBABA_CLOUD_OIDC_PROVIDER_ARN: the ARN of the OIDC IdP.

ALIBABA_CLOUD_OIDC_TOKEN_FILE: the path of the OIDC token file.

Note

Make sure that the version of credentials-java is 0.2.10 or later.

import com.aliyun.credentials.Client;
import com.aliyun.credentials.models.Config;

public class DemoTest {

  public static void main(String[] args) throws Exception {
    Config credentialConfig = new Config();
    credentialConfig.setType("oidc_role_arn");
    // Specify the ARN of the RAM role by using the ALIBABA_CLOUD_ROLE_ARN environment variable.
    credentialConfig.setRoleArn("<RoleArn>");
    // Specify the ARN of the OIDC IdP by specifying the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
    credentialConfig.setOidcProviderArn("<OidcProviderArn>");
    // Specify the path of the OIDC token file by specifying the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
    credentialConfig.setOidcTokenFilePath("<OidcTokenFilePath>");
    // Specify the role session name. You can obtain the value from the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
    credentialConfig.setRoleSessionName("<RoleSessionName>");
    // Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    credentialConfig.setPolicy("<Policy>");
    // Specify the validity period of the session.
    credentialConfig.setRoleSessionExpiration(3600);
    Client credentialClient = new Client(credentialConfig);
    // No value is specified for new Client().
  }
}

Call example

The following example shows how to call the DescribeRegions operation of ECS. You must first install ECS SDK.

import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.DescribeRegionsRequest;
import com.aliyun.ecs20140526.models.DescribeRegionsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

public class Sample {
    public static void main(String[] args) throws Exception {
        // Use the RAM role of an OIDC IdP to initialize a Credentials client.
        com.aliyun.credentials.models.Config credentialsConfig = new com.aliyun.credentials.models.Config();
        // Specify the type of the credential.
        credentialsConfig.setType("oidc_role_arn");
        // Specify the ARN of the RAM role by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable.
        credentialsConfig.setRoleArn("<RoleArn>");
        // Specify the ARN of the OIDC IdP. You can obtain the ARN from the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
        credentialsConfig.setOidcProviderArn("<OidcProviderArn>");
        // Specify the path of the OIDC token file. You can obtain the value from the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
        credentialsConfig.setOidcTokenFilePath("<OidcTokenFilePath>");
        // Specify the role session name. You can obtain the value from the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
        credentialsConfig.setRoleSessionName("<RoleSessionName>");
        // Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
        credentialsConfig.setPolicy("<Policy>");
        // Specify the validity period of the session
        credentialsConfig.setRoleSessionExpiration(3600);
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client(credentialsConfig);

        // Use the Credentials client to initialize the ECS SDK client.
        Config ecsConfig = new Config();
        ecsConfig.setCredential(credentialClient);
        ecsConfig.setEndpoint("ecs.aliyuncs.com");
        Client ecsClient = new Client(ecsConfig);
        // Initialize a request to call the DescribeRegions operation.
        DescribeRegionsRequest describeInstancesRequest = new DescribeRegionsRequest();
        // Initialize the runtime configuration.
        RuntimeOptions runtime = new RuntimeOptions();
        // Call the DescribeRegions operation and obtain a response.
        DescribeRegionsResponse response = ecsClient.describeRegionsWithOptions(describeInstancesRequest, runtime);
        System.out.println(response.body.toMap());
    }
}

Method 7: Use a URI

By encapsulating an STS token service within an application and providing a custom URI for external access, other services can obtain STS tokens only through this URI, which effectively reduces the risk of exposing information such as AccessKey pairs. The Credentials tool supports obtaining STS tokens by requesting this service URI, thereby initializing the Credentials client.

import com.aliyun.credentials.Client;
import com.aliyun.credentials.models.Config;

public class DemoTest {
    public static void main(String[] args) throws Exception {
        Config credentialConfig = new Config();
        credentialConfig.setType("credentials_uri");
        // Specify the URI of the credential in the http://local_or_remote_uri/ format. You can obtain the value from the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
        credentialConfig.setCredentialsUri("<CredentialsUri>");
        Client credentialClient = new Client(credentialConfig);
        // No value is specified for new Client().
    }
}

The URI must meet the following requirements:

  • GET requests are supported.

  • The response status code is 2XX.

  • The following response body structure is used:

    {
      "Code": "Success",
      "AccessKeySecret": "AccessKeySecret",
      "AccessKeyId": "AccessKeyId",
      "Expiration": "2021-09-26T03:46:38Z",
      "SecurityToken": "SecurityToken"
    }

Call example

The following example shows how to call the DescribeRegions operation of ECS. You must first install ECS SDK.

import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.DescribeRegionsRequest;
import com.aliyun.ecs20140526.models.DescribeRegionsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

public class Sample {
    public static void main(String[] args) throws Exception {
        // Use a URI to initialize a Credentials client.
        com.aliyun.credentials.models.Config credentialsConfig = new com.aliyun.credentials.models.Config();
        // Specify the type of the credential.
        credentialsConfig.setType("credentials_uri");
        // Obtain the URI of the credential in the http://local_or_remote_uri/ format by specifying the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
        credentialsConfig.setCredentialsUri("<CredentialsUri>");
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client(credentialsConfig);

        // Use the Credentials client to initialize the ECS SDK client.
        Config ecsConfig = new Config();
        ecsConfig.setCredential(credentialClient);
        ecsConfig.setEndpoint("ecs.aliyuncs.com");
        Client ecsClient = new Client(ecsConfig);
        // Initialize a request to call the DescribeRegions operation.
        DescribeRegionsRequest describeInstancesRequest = new DescribeRegionsRequest();
        // Initialize the runtime configuration.
        RuntimeOptions runtime = new RuntimeOptions();
        // Call the DescribeRegions operation and obtain a response.
        DescribeRegionsResponse response = ecsClient.describeRegionsWithOptions(describeInstancesRequest, runtime);
        System.out.println(response.body.toMap());
    }
}

Method 8: Use a bearer token

Currently, only the Cloud Call Center (CCC) product supports initializing credentials by using bearer tokens.

import com.aliyun.credentials.Client;
import com.aliyun.credentials.models.Config;

public class DemoTest {
    public static void main(String[] args) throws Exception {
        Config credentialConfig = new Config();
        credentialConfig.setType("bearer");
        // Enter the bearer token
        credentialConfig.setBearerToken("<BearerToken>");
        Client credentialClient = new Client(credentialConfig);
        // No value is specified for new Client().
    }
}

Call example

The following example shows how to call the GetInstance operation of CCC. You must first install CCC SDK.

import com.aliyun.ccc20200701.Client;
import com.aliyun.ccc20200701.models.GetInstanceRequest;
import com.aliyun.ccc20200701.models.GetInstanceResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

public class Sample {
    public static void main(String[] args) throws Exception {
        // Use a bearer token to initialize a Credentials client.
        com.aliyun.credentials.models.Config credentialsConfig = new com.aliyun.credentials.models.Config();
        // Specify the type of the credential.
        credentialsConfig.setType("bearer");
        // Specify the bearer token that is automatically generated by the server. The bearer token has a validity period.
        credentialsConfig.setBearerToken("<bearer_token>");
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client(credentialsConfig);

        // Use the Credentials client to initialize the ECS SDK client.
        Config cccConfig = new Config();
        cccConfig.setCredential(credentialClient);
        cccConfig.setEndpoint("ccc.aliyuncs.com");
        Client cccClient = new Client(cccConfig);
        // Call the API
        GetInstanceRequest getInstanceRequest = new GetInstanceRequest().setInstanceId("ccc-test");
        // Initialize the runtime configuration.
        RuntimeOptions runtime = new RuntimeOptions();
        GetInstanceResponse response = cccClient.getInstanceWithOptions(getInstanceRequest, runtime);
        System.out.println(response.body.toMap());
    }
}

Default credential provider chain

If you want to use different types of credentials in the development and production environments of your application, you generally need to obtain the environment information from the code and write code branches to obtain different credentials for the development and production environments. The default credential provider chain of Alibaba Cloud Credentials for Java allows you to obtain credentials for different environments based on configurations independent of the application, without the need for code modification. When you initialize a Credentials client without specifying a method by using Client client = new Client(), Alibaba Cloud SDK attempts to find the relevant credential information in the following order.

1. Using system properties

The Credentials tool first obtains the credential information from system properties.

  • If alibabacloud.accessKeyId and alibabacloud.accessKeySecret are defined in system properties, an AccessKey pair is used as the access credential.

  • If alibabacloud.accessKeyId, alibabacloud.accessKeySecret, and alibabacloud.sessionToken are defined in system properties, an STS token is used as the access credential.

You can add the following JVM parameters to specify values for the preceding attributes when you run a Java application:

-Dalibabacloud.accessKeyId=your-access-key-id -Dalibabacloud.accessKeySecret=your-access-key-secret

2. Obtain the credential information from environment variables

If no credential information is found in the system attributes, the Credentials tool continues to check the environment variables.

  • If ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET exist and are not empty, they are used as the default credential.

  • If ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and ALIBABA_CLOUD_SECURITY_TOKEN are set, an STS token is used as the default credential.

3. Obtain the credential information by using the RAM role of an OIDC IdP

If no credentials with a higher priority are found, the Credentials tool checks the following environment variables that are related to the RAM role of the OIDC IdP:

  • ALIBABA_CLOUD_ROLE_ARN: the ARN of the RAM role.

  • ALIBABA_CLOUD_OIDC_PROVIDER_ARN: the ARN of the OIDC IdP.

  • ALIBABA_CLOUD_OIDC_TOKEN_FILE: the path of the OIDC token file.

If all the preceding three variables are set and valid, the Credentials tool uses the values of the variables to call the AssumeRoleWithOIDC operation of STS to exchange for an STS token as the default credential.

4. Obtain the credential information from the config.json file

Note

Make sure that the version of credentials-java is 0.3.8 or later.

If no credentials with a higher priority are found, the Credentials tool attempts to load the config.json file. Default file path:

  • Linux: ~/.aliyun/config.json

  • Windows: C:\Users\USER_NAME\.aliyun\config.json

Do not change the preceding default paths. If you want to use this method to configure an access credential, manually create a config.json file in the corresponding path. Example:

{
	"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
		}
	]
}

You can specify different credentials by using mode in the config.json file:

  • AK: uses the AccessKey pair of a RAM user to obtain the credential information.

  • StsToken: uses an STS token to obtain the credential information.

  • RamRoleArn: uses the ARN of a RAM role to obtain the credential information.

  • EcsRamRole: uses the RAM role attached to an ECS instance to obtain the credential information.

  • OIDC: uses the ARN of an OIDC IdP and the OIDC token file to obtain the credential information.

  • ChainableRamRoleArn: uses a role chain and specifies an access credential in another JSON file to obtain the credential information.

Note

name specifies the name of the credential. Modify other parameters based on your business requirements.

After the configuration is complete, the Credentials tool initializes the Credentials client based on the credential name specified by current in the configuration file. You can also specify a specific credential name by using the ALIBABA_CLOUD_PROFILE environment variable. For example, you can set the value of ALIBABA_CLOUD_PROFILE to client1.

5. Obtain the credential information by using the RAM role of an ECS instance

If no credentials with a higher priority are found, the Credentials tool attempts to use the RAM role assigned to the ECS instance to obtain a credential. By default, the Credentials tool accesses the metadata server of ECS in security hardening mode (IMDSv2) to obtain the STS token of the RAM role used by the ECS instance and uses the STS token as the default credential. The Credentials tool automatically accesses the metadata server of ECS to obtain the name of the RAM role (RoleName) and then obtains the credential. Two requests are sent in this process. To reduce the number of requests, you can directly configure the ALIBABA_CLOUD_ECS_METADATA environment variable to specify the name of the RAM role of the instance. If an exception occurs in the security hardening mode, the Credentials tool obtains the access credential in normal mode. You can also set the ALIBABA_CLOUD_IMDSV1_DISABLE environment variable to specify how to handle exceptions:

  1. false: The Credentials tool continues to obtain the access credential in normal mode.

  2. true: The exception is thrown and the Credentials tool continues to obtain the access credential in security hardening mode.

The configurations for the metadata server determine whether the server supports the security hardening mode.

You can also configure the ALIBABA_CLOUD_ECS_METADATA_DISABLED=true environment variable to disable access to ECS instance metadata.

Note
Note

To obtain an access credential in security hardening mode (IMDSv2), make sure that the version of credentials-java is 0.3.10 or later.

6. Obtain the credential information by using a URI

If no valid credential information is found by using the preceding methods, the Credentials tool checks the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. If this variable exists and points to a valid URI, the Credentials tool sends an HTTP request to the URI to obtain a temporary security credential as the default credential.

Auto-refresh mechanism for session credentials

Session credentials include ARNs of RAM roles (RamRoleArn), RAM roles of ECS instances, RAM roles of OIDC IdPs (OIDCRoleArn), and credential URIs. The Credentials tool provides a built-in automatic update mechanism for session credentials. After a credential is obtained from the first call, the Credentials tool stores the credential in the cache. In subsequent calls, the credential is read from the cache as long as the credential is not expired. Otherwise, the Credentials tool makes a call to obtain the credential again, and updates the credential in the cache.

Note

For RAM roles of ECS instances, the Credentials tool updates the credential 15 minutes before the cache time-to-live (TTL) ends.

The following example shows how to create a Credentials client by using the singleton pattern and use the Credentials client to initialize an SDK client. Then, the example shows how to call an API operation at different time intervals to verify whether the internal cache is used and whether the credential is refreshed after the cache expires.

import com.aliyun.credentials.models.CredentialModel;
import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.DescribeRegionsRequest;
import com.aliyun.ecs20140526.models.DescribeRegionsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

import java.util.Date;
import java.util.concurrent.*;

public class Sample {

    /**
     * Credential class used to manage Alibaba Cloud credential instances, using the singleton pattern.
     */
    private static class Credential {
        private static volatile com.aliyun.credentials.Client instance;

        private Credential() {
        }

        public static com.aliyun.credentials.Client getInstance() {
            if (instance == null) {
                synchronized (Credential.class) {
                    if (instance == null) {
                        try {
                            com.aliyun.credentials.models.Config config = new com.aliyun.credentials.models.Config();
                            config.setType("ram_role_arn");
                            config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
                            config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
                            config.setRoleArn(System.getenv("ALIBABA_CLOUD_ROLE_ARN"));
                            config.setRoleSessionName("RamRoleArnTest");
                            config.setRoleSessionExpiration(3600);
                            instance = new com.aliyun.credentials.Client(config);
                        } catch (Exception e) {
                            throw new RuntimeException("Credential initialization failed: " + e.getMessage(), e);
                        }
                    }
                }
            }
            return instance;
        }
    }

    /**
     * EcsClient class used to manage ECS clients, using the singleton pattern.
     */
    private static class EcsClient {
        private static volatile Client instance;

        private EcsClient() {
        }

        public static Client getInstance(com.aliyun.credentials.Client credentialClient) {
            if (instance == null) {
                synchronized (EcsClient.class) {
                    if (instance == null) {
                        try {
                            Config ecsConfig = new Config();
                            ecsConfig.setEndpoint("ecs.cn-hangzhou.aliyuncs.com");
                            ecsConfig.setCredential(credentialClient);
                            instance = new Client(ecsConfig);
                        } catch (Exception e) {
                            throw new RuntimeException("ECS client initialization failed: " + e.getMessage(), e);
                        }
                    }
                }
            }
            return instance;
        }
    }

    public static void main(String[] args) {
        // Use ThreadPoolExecutor to create a scheduled thread pool
        ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(
                1,
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
        scheduler.setKeepAliveTime(0L, TimeUnit.SECONDS);
        scheduler.allowCoreThreadTimeOut(false); // Do not allow core threads to time out

        // Define a Runnable task to execute the call logic
        Runnable task = () -> {
            try {
                com.aliyun.credentials.Client credentialClient = Credential.getInstance();
                CredentialModel credential = credentialClient.getCredential();
                System.out.println(new Date());
                System.out.printf("AK ID:%s, AK Secret:%s, STS Token:%s%n", credential.accessKeyId, credential.accessKeySecret, credential.securityToken);

                // This example calls the ECS API to verify that the credential is valid. You can modify this based on your requirements.
                Client ecsClient = EcsClient.getInstance(credentialClient);
                DescribeRegionsRequest request = new DescribeRegionsRequest();
                RuntimeOptions runtime = new RuntimeOptions();
                DescribeRegionsResponse response = ecsClient.describeRegionsWithOptions(request, runtime);
                System.out.printf("Invoke result:%s%n", response.statusCode);
            } catch (Exception e) {
                throw new RuntimeException("ECS client execution failed: " + e.getMessage(), e);
            }
        };

        try {
            // First task execution (immediate execution)
            scheduler.execute(task);
            // Second task execution, delayed by 600 seconds
            scheduler.schedule(task, 600, TimeUnit.SECONDS);
            // Third task execution, delayed by 3600 seconds after the second execution
            scheduler.schedule(task, 4200, TimeUnit.SECONDS);
            // Fourth task execution, delayed by 100 seconds after the third execution
            scheduler.schedule(task, 4300, TimeUnit.SECONDS);
        } finally {
            // Shut down the thread pool, ensuring all tasks are completed before shutdown
            scheduler.shutdown();
            try {
                if (!scheduler.awaitTermination(4500, TimeUnit.SECONDS)) {
                    scheduler.shutdownNow();
                }
            } catch (InterruptedException e) {
                scheduler.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }
}

image

Based on the log results, the following analysis can be made:

  • In the first call, the system obtains credential information based on the configuration because no credential is cached. After the credential is obtained, it is stored in the cache.

  • The credential information used in the second call is the same as that in the first call, which indicates that the credential information is retrieved from the cache in the second call.

  • In the third call, the credential in the cache has expired because the validity period of the credential (RoleSessionExpiration) is set to 3600 seconds and the third call occurs 4200 seconds after the first call. Therefore, the SDK automatically refreshes the credential based on the auto-refresh mechanism, obtains a new credential, and stores the new credential in the cache.

  • The credential information used in the fourth call is the same as the newly obtained credential information in the third call, which indicates that the credential in the cache has been updated with the new credential after the old credential expired.

References