All Products
Search
Document Center

Alibaba Cloud SDK:Manage access credentials

Last Updated:Aug 09, 2024

When you call API operations to manage cloud resources by using Alibaba Cloud SDKs, you must configure valid credential information. The Alibaba Cloud Credentials tool provides a powerful set of features that allow you to easily obtain and manage access credentials. This topic describes how to use the Credentials tool to configure various types of credentials such as the default credential, AccessKey pairs, or Security Token Service (STS) tokens. This topic also describes the order based on which the Credentials tool obtains the default credential. You can develop a thorough knowledge of configuring and managing credentials in Alibaba Cloud SDKs. This ensures that your operations on cloud resources are efficient and secure.

Background information

A credential is a set of information that is 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. An AccessKey pair of an Alibaba Cloud account or a Resource Access Management (RAM) user. An AccessKey pair is permanently valid. It consists of an AccessKey ID and an AccessKey secret.

  2. An STS token of a RAM role. An STS token is a temporary credential. You can specify a validity period and access permissions for an STS token. For more information, see What is STS?

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

Prerequisites

  • Java Development Kit (JDK) 1.8 or later is installed.

  • Alibaba Cloud SDK V2.0 is installed. For more information, see Use Alibaba Cloud SDKs for Java in an IDE.

  • The in-house SDKs of services that use self-managed gateways are not installed.

Install the Credentials tool

Install Alibaba Cloud Credentials for Java by adding the following Maven dependency:

<dependency>
   <groupId>com.aliyun</groupId>
   <artifactId>credentials-java</artifactId>
   <version>LATEST</version>
</dependency>
  1. We recommend that you use the latest version of Alibaba Cloud Credentials for Java.

  2. For information about all released versions of Alibaba Cloud Credentials for Java, see ChangeLog.txt.

  3. We recommend that you use Alibaba Cloud SDK V2.0. If you do not use Alibaba Cloud SDK V2.0, you must also add the following dependency. Otherwise, an error is reported to indicate that the com.aliyun.tea.TeaModel class file does not exist.

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>tea</artifactId>
      <version>LATEST</version>
    </dependency>

Initialize a Credentials client

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

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, see the Default credential provider chain section of this topic.

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

public class DemoTest {
    public static void main(String[] args) throws Exception{
        // Do not specify a method to initialize a Credentials client.
        Config credentialConfig = new Config();
        Client credentialClient = new Client(credentialConfig);
    }
}

Call example

You can use the default credential provider chain to automatically create access credentials and call the API operations of Alibaba Cloud services without the need to use a hard-coded AccessKey pair.

The following sample code provides an example on how to call the DescribeRegions operation of Elastic Compute Service (ECS). Before you call this operation, you must install ECS SDK for Java.

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();

        Config ecsConfig = new Config();
        // Specify the endpoint of the cloud service. 
        ecsConfig.setEndpoint("ecs.aliyuncs.com");
        // Use the SDK Credentials package to configure a credential. 
        ecsConfig.setCredential(credentialClient);
        // Initialize the ECS SDK client. 
        Client ecsClient = new Client(ecsConfig);
        // Initialize the request to call the DescribeRegions operation. 
        DescribeRegionsRequest describeInstancesRequest = new DescribeRegionsRequest();
        // Initialize the runtime configurations. 
        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

You can create an AccessKey pair that is used to call API operations for your Alibaba Cloud account or a RAM user. For more information, see Create an AccessKey pair. Then, you can use the AccessKey pair to initialize a Credentials client.

Warning

An Alibaba Cloud account has full access to all resources of 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 minimum necessary permissions 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);
    }
}

Call example

You can use the Credentials tool to read an AccessKey pair and call the API operations of Alibaba Cloud services.

The following sample code provides an example on how to call the DescribeRegions operation of Elastic Compute Service (ECS). Before you call this operation, you must install ECS SDK for Java.

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);

        Config ecsConfig = new Config();
        // Specify the endpoint of the cloud service. 
        ecsConfig.setEndpoint("ecs.aliyuncs.com");
        // Use the SDK Credentials package to configure a credential. 
        ecsConfig.setCredential(credentialClient);
        // Initialize the ECS SDK client. 
        Client ecsClient = new Client(ecsConfig);
        // Initialize the request to call the DescribeRegions operation. 
        DescribeRegionsRequest describeInstancesRequest = new DescribeRegionsRequest();
        // Initialize the runtime configurations. 
        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

You can call the AssumeRole operation of STS as a RAM user to obtain an STS token. You can specify the maximum validity period of the STS token. The following sample code provides an example on how to initialize a Credentials client by using an STS token. The example does not show how to obtain an STS token.

{
  "RequestId": "EA7A3526-F7DB-54A5-8300-9B742CFAA5EA",
  "AssumedRoleUser": {
    "Arn": "acs:ram::125499367423****:role/STStokenTestRole/STSsessionName",
    "AssumedRoleId": "35219123109646****:STSsessionName"
  },
  "Credentials": {
    "SecurityToken": "exampleToken",
    "AccessKeyId": "STS.exampleAccessKeyID",
    "AccessKeySecret": "exampleAccessKeySecret",
    "Expiration": "2023-03-26T05:26:06Z"
  }
}
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("sts");
      	// Replace <ALIBABA_CLOUD_ACCESS_KEY_ID> with the temporary AccessKey ID that is obtained from the response to the AssumeRole operation. 
        credentialConfig.setAccessKeyId("<ALIBABA_CLOUD_ACCESS_KEY_ID>");
      	// Replace <ALIBABA_CLOUD_ACCESS_KEY_SECRET> with the temporary AccessKey secret that is obtained from the response to the AssumeRole operation. 
        credentialConfig.setAccessKeySecret("<ALIBABA_CLOUD_ACCESS_KEY_SECRET>");
      	// Replace <ALIBABA_CLOUD_SECURITY_TOKEN> with the STS token that is obtained from the response to the AssumeRole operation. 
        credentialConfig.setSecurityToken("<ALIBABA_CLOUD_SECURITY_TOKEN>");
        Client credentialClient = new Client(credentialConfig);
    }
}

Call example

You can use the Credentials tool to read an STS token and call the API operations of Alibaba Cloud services.

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for Java and STS SDK for Java.

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 {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured. 
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. 
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Specify the endpoint. For more information, visit https://api.aliyun.com/product/Sts.
        config.endpoint = "sts.cn-hangzhou.aliyuncs.com";
        // Create an StsClient object.
        Client client = new Client(config);
        AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest()
                .setRoleArn("acs:ram::125499367423****:role/STStokenTestRole/STSsessionName")
                .setRoleSessionName("35219123109646****:STSsessionName");
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            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();
            // Specify the type of the credential. 
            credentialsConfig.setType("sts");
            credentialsConfig.setAccessKeyId(assumeRoleResponseBodyCredentials.accessKeyId);
            credentialsConfig.setAccessKeySecret(assumeRoleResponseBodyCredentials.accessKeySecret);
            credentialsConfig.setSecurityToken(assumeRoleResponseBodyCredentials.securityToken);
            com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client(credentialsConfig);

            // Create an ECS SDK client. 
            Config ecsConfig = new Config();
            // Specify the endpoint of the cloud service. 
            ecsConfig.setEndpoint("ecs.aliyuncs.com");
            // Use the SDK Credentials package to configure a credential. 
            ecsConfig.setCredential(credentialClient);
            com.aliyun.ecs20140526.Client ecsClient = new com.aliyun.ecs20140526.Client(ecsConfig);
            // Initialize the request to call the DescribeRegions operation. 
            DescribeRegionsRequest describeInstancesRequest = new DescribeRegionsRequest();
            // Initialize the runtime configurations. 
            RuntimeOptions describeRegionsRuntime = new RuntimeOptions();
            // Call the DescribeRegions operation and obtain a response. 
            DescribeRegionsResponse response = ecsClient.describeRegionsWithOptions(describeInstancesRequest, describeRegionsRuntime);
            System.out.println(response.body.toMap());
        } catch (com.aliyun.tea.TeaException error) {
            // Display an error message.
            System.out.println(error.getMessage());
            // The URL of the corresponding error diagnostics page.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception ex) {
            // Display an error message.
            System.out.println(ex.getMessage());
        }
    }
}

Method 4: Use an AccessKey pair and a RAM role

The underlying logic of this method is to use an STS token to initialize a Credentials client. After you specify the Alibaba Cloud Resource Name (ARN) of a RAM role, the Credentials tool can obtain an STS token from STS. You can also use the setPolicy method to limit the permissions of the 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.
    credentialConfig.setRoleArn("<RoleArn>");
    // Specify the name of the role session.
    credentialConfig.setRoleSessionName("<RoleSessionName>");
    // Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}.
    credentialConfig.setPolicy("<Policy>");
    credentialConfig.setRoleSessionExpiration(3600);
    Client credentialClient = new Client(credentialConfig);
  }
}

Call example

The following sample code provides an example on how to call the DescribeRegions operation of Elastic Compute Service (ECS). Before you call this operation, you must install ECS SDK for Java.

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();
        // Specify the type of the credential. 
        credentialsConfig.setType("ram_role_arn");
        // 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"));
        // Specify the ARN of the RAM role to be assumed. Example: acs:ram::123456789012****:role/adminrole.
        credentialsConfig.setRoleArn("<RoleArn>");
        // Specify the name of the role session.
        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);

        Config ecsConfig = new Config();
        // Specify the endpoint of the cloud service. 
        ecsConfig.setEndpoint("ecs.aliyuncs.com");
        // Use the SDK Credentials package to configure a credential. 
        ecsConfig.setCredential(credentialClient);
        // Initialize the ECS SDK client. 
        Client ecsClient = new Client(ecsConfig);
        // Initialize the request to call the DescribeRegions operation. 
        DescribeRegionsRequest describeInstancesRequest = new DescribeRegionsRequest();
        // Initialize the runtime configurations. 
        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: Use the RAM role of an ECS instance and access the metadata of the ECS instance in normal mode

The underlying logic of this method is to use an STS token to initialize a Credentials client. The Credentials tool automatically obtains the RAM role attached to an ECS instance and uses the metadata server of ECS to obtain an STS token. The STS token is then used to initialize a Credentials client. You can also attach a RAM role to an elastic container instance or a worker node in an Container Service for Kubernetes cluster.

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.
        credentialConfig.setRoleName("<RoleName>");
        Client credentialClient = new Client(credentialConfig);
    }
}

Call example

The following sample code provides an example on how to call the DescribeRegions operation of Elastic Compute Service (ECS). Before you call this operation, you must install ECS SDK for Java.

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.
        credentialsConfig.setRoleName("<RoleName>");
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client(credentialsConfig);

        Config ecsConfig = new Config();
        // Specify the endpoint of the cloud service. 
        ecsConfig.setEndpoint("ecs.aliyuncs.com");
        // Use the SDK Credentials package to configure a credential. 
        ecsConfig.setCredential(credentialClient);
        // Initialize the ECS SDK client. 
        Client ecsClient = new Client(ecsConfig);
        // Initialize the request to call the DescribeRegions operation. 
        DescribeRegionsRequest describeInstancesRequest = new DescribeRegionsRequest();
        // Initialize the runtime configurations. 
        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 ECS instance and access the metadata of the ECS instance in security hardening mode

You can access the metadata of an ECS instance in security hardening mode and obtain the initial credential of the RAM role that is attached to the ECS instance. Compared with the normal mode, the security hardening mode implements the following security logic that is more rigorous: First, a token that has a validity period is automatically generated inside the ECS instance. Then, this token is used as a credential to request an STS token from the metadata server. These operations also constitute the secure initialization process of a Credentials client.

In security hardening mode, the token generated inside the ECS instance is dynamic and has a validity period. In this case, external attackers cannot illegally access the metadata server by predicting or forging a token. This effectively prevents network security risks such as server-side request forgery (SSRF). The security hardening mode not only adds an extra layer of protection to identity verification, but also significantly improves the security of the overall system. This mode ensures the secure access to and management of cloud resources.

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

public class DemoTest {
    public static void main(String[] args) {
        Config credentialConfig = new Config();
        // Which type of credential you want
        credentialConfig.setType("ecs_ram_role");
        // `roleName` is optional. It will be retrieved automatically if not set. It is highly recommended to set it up to reduce requests
        credentialConfig.setRoleName("RoleName");
        // `enableIMDSv2` is optional and is recommended to be turned on. It can be replaced by setting environment variable: ALIBABA_CLOUD_ECS_IMDSV2_ENABLE
        credentialConfig.setEnableIMDSv2(true);
        Client credentialClient = new Client(credentialConfig);
    }
}
Important
  • The default value of the EnableIMDSv2 parameter is false, which specifies that the metadata of the ECS instance is accessed in normal mode.

  • If you want to access the metadata of the ECS instance in security hardening mode, set the EnableIMDSv2 parameter to true.

Call example

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.
        credentialsConfig.setRoleName("<RoleName>");
        // Optional. Specifies whether to access the metadata of the ECS instance in security hardening mode.
        credentialsConfig.setEnableIMDSv2(true);
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client(credentialsConfig);

        Config ecsConfig = new Config();
        // Specify the endpoint of the cloud service. 
        ecsConfig.setEndpoint("ecs.aliyuncs.com");
        // Use the SDK Credentials package to configure a credential. 
        ecsConfig.setCredential(credentialClient);
        // Initialize the ECS SDK client. 
        Client ecsClient = new Client(ecsConfig);
        // Initialize the request to call the DescribeRegions operation. 
        DescribeRegionsRequest describeInstancesRequest = new DescribeRegionsRequest();
        // Initialize the runtime configurations. 
        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 the RAM role of an OIDC IdP

After you attach a RAM role to a worker node in an Container Service for Kubernetes, applications in the pods on the worker node can use the metadata server to obtain an STS token the same way in which applications on ECS instances do. 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 and enable untrusted applications to securely obtain required STS tokens, you can use the RAM Roles for Service Accounts (RRSA) feature to grant minimum necessary permissions to an application. In this case, the ACK cluster creates a service account OpenID Connect (OIDC) token file, associates the token file with a pod, and then injects relevant environment variables into the pod. Then, the Credentials tool uses the environment variables to call the AssumeRoleWithOIDC operation of STS and obtains an STS token of the RAM role. For more information about the RRSA feature, see Use RRSA to authorize different pods to access different cloud services.

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 identity provider (IdP).

ALIBABA_CLOUD_OIDC_TOKEN_FILE: the path of the OIDC token file.

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");
    credentialConfig.setRoleArn(System.getenv("ALIBABA_CLOUD_ROLE_ARN"));
    credentialConfig.setOidcProviderArn(System.getenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN"));
    credentialConfig.setOidcTokenFilePath(System.getenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE"));
    // Specify the name of the role session.
    credentialConfig.setRoleSessionName("<RoleSessionName>");
    // Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}.
    credentialConfig.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.
    credentialConfig.setExternalId("<ExternalId>");
    // Specify the validity period of the session.
    credentialConfig.setRoleSessionExpiration(3600);
    Client credentialClient = new Client(credentialConfig);
  }
}

Call example

The following sample code provides an example on how to call the DescribeRegions operation of Elastic Compute Service (ECS). Before you call this operation, you must install ECS SDK for Java.

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");
        credentialsConfig.setRoleArn(System.getenv("ALIBABA_CLOUD_ROLE_ARN"));
        credentialsConfig.setOidcProviderArn(System.getenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN"));
        credentialsConfig.setOidcTokenFilePath(System.getenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE"));
        // Specify the name of the role session.
        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);

        Config ecsConfig = new Config();
        // Specify the endpoint of the cloud service. 
        ecsConfig.setEndpoint("ecs.aliyuncs.com");
        // Use the SDK Credentials package to configure a credential. 
        ecsConfig.setCredential(credentialClient);
        // Initialize the ECS SDK client. 
        Client ecsClient = new Client(ecsConfig);
        // Initialize the request to call the DescribeRegions operation. 
        DescribeRegionsRequest describeInstancesRequest = new DescribeRegionsRequest();
        // Initialize the runtime configurations. 
        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 URI

The underlying logic of this method is to use an STS token to initialize a Credentials client. The Credentials tool uses the uniform resource identifier (URI) that you provide to obtain an STS token. The STS token is then used 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("credentials_uri");
        // The URI of the credential, in the format of http://local_or_remote_uri/.
        credentialConfig.setCredentialsUri("<local_or_remote_uri>");
        Client credentialClient = new Client(credentialConfig);
    }
}

Call example

To call the API operations of Alibaba Cloud services, you can specify a local or remote URI for credentials and use the Credentials tool to obtain and automatically update an STS token based on the local or remote URI.

To call the API operations of an Alibaba Cloud service, you must install dependencies for the Alibaba Cloud service. The following sample code provides an example on how to call the DescribeRegions operation of Elastic Compute Service (ECS). Before you call this operation, you must install ECS SDK for Java.

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");
        // Specify the URI of the credential, in the format of http://local_or_remote_uri/. 
        credentialsConfig.setCredentialsUri("<local_or_remote_uri>");
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client(credentialsConfig);

        Config ecsConfig = new Config();
        // Specify the endpoint of the cloud service. 
        ecsConfig.setEndpoint("ecs.aliyuncs.com");
        // Use the SDK Credentials package to configure a credential. 
        ecsConfig.setCredential(credentialClient);
        // Initialize the ECS SDK client. 
        Client ecsClient = new Client(ecsConfig);
        // Initialize the request to call the DescribeRegions operation. 
        DescribeRegionsRequest describeInstancesRequest = new DescribeRegionsRequest();
        // Initialize the runtime configurations. 
        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 9: Use a bearer token

Only Cloud Call Center allows you to use a bearer token 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("bearer");
        // Enter the bearer token.
        credentialConfig.setBearerToken("<BearerToken>");
        Client credentialClient = new Client(credentialConfig);
    }
}

Call example

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install Cloud Call Center SDK for Python.

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);

        Config cccConfig = new Config();
        // Specify the endpoint of the cloud service. 
        cccConfig.setEndpoint("ccc.aliyuncs.com");
        // Use the SDK Credentials package to configure a credential. 
        cccConfig.setCredential(credentialClient);
        Client cccClient = new Client(cccConfig);
        GetInstanceRequest getInstanceRequest = new GetInstanceRequest().setInstanceId("ccc-test");
        // Initialize the runtime configurations. 
        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 use the same code to obtain credentials for different environments based on configurations independent of the application. If you use Client client = new Client() to initialize a Credentials client without specifying an initialization method, the Credentials tool obtains the credential information in the following order:

1. Obtain the credential information from system properties

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

If the alibabacloud.accessKeyId (AccessKey ID) and alibabacloud.accessKeyIdSecret (AccessKey secret) system properties are specified, the Credentials tool uses the specified AccessKey pair as the default credential.

You can add the -Dalibabacloud.accessKeyId=*** and -Dalibabacloud.accessKeyIdSecret=*** properties to specify the credential when you run your Java application.

2. Obtain the credential information from environment variables

If no credentials are found in the previous step, the Credentials tool obtains the credential information from environment variables.

  • If the ALIBABA_CLOUD_ACCESS_KEY_ID (AccessKey ID) and ALIBABA_CLOUD_ACCESS_KEY_SECRET (AccessKey secret) system environment variables are specified, the Credentials tool uses the specified AccessKey pair as the default credential.

  • If the ALIBABA_CLOUD_ACCESS_KEY_ID (AccessKey ID), ALIBABA_CLOUD_ACCESS_KEY_SECRET (AccessKey secret), and ALIBABA_CLOUD_SECURITY_TOKEN (STS token) system environment variables are specified, the Credentials tool uses the specified STS token as the default credential.

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

If no credentials are found in the previous step, the Credentials tool obtains the values of the following environment variables:

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 the preceding three environment variables are specified, the Credentials tool uses the environment variables to call the AssumeRoleWithOIDC operation of STS to obtain an STS token as the default credential.

4. Obtain the credential information from a configuration file

If no credentials are found in the previous step, the Credentials tool obtains the credential information from a configuration file. The path of the configuration file varies based on the operating system:

Linux: ~/.alibabacloud/credentials

Windows: C:\Users\USER_NAME\.alibabacloud\credentials

You can also specify the configuration file path by configuring the ALIBABA_CLOUD_CREDENTIALS_FILE environment variable. If the configuration file exists, the application initializes a Credentials client by using the credential information that is specified by default in the configuration file. You can also configure the ALIBABA_CLOUD_PROFILE environment variable to modify the default credential information that is read.

Configuration example:

[default]
enable=true
type=access_key
access_key_id=<ALIBABA_CLOUD_ACCESS_KEY_ID>
access_key_secret=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>

[client1]
enable=true
type=sts
access_key_id=<ALIBABA_CLOUD_ACCESS_KEY_ID>
access_key_secret=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>
security_token=<security_token>

[client2]
enable=true
type=ecs_ram_role
role_name=<ecs_ram_role_name>

[client3]
enable=true
type=ram_role_arn
policy=<policy_name>
access_key_id=<ALIBABA_CLOUD_ACCESS_KEY_ID>
access_key_secret=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>
role_arn=<ram_role_arn>
role_session_name=<role_session_name>

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

If no credentials are found in the previous step, the Credentials tool obtains the value of the ALIBABA_CLOUD_ECS_METADATA environment variable that specifies the RAM role name of an ECS instance. If the RAM role exists, the application obtains an STS token of the RAM role as the default credential by using the metadata server of ECS.

Protect credential information

Credential leaks may expose the system to attacks. This is one of the main threats to cloud services. To prevent the leaks of plaintext credential information and reduce security risks, you can use the following solutions:

  1. We recommend that you use the RAM role of an ECS instance or an STS token.

  2. We recommend that you use the default credential provider chain and record the credential information in environment variables or a configuration file.

  3. To use an explicit initialization method to initialize a Credentials client, we recommend that you use system properties or environment variables to record the credential information and obtain the credential information by using the System.getProperty or System.getenv method.

    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);
        }
    }

Switch between credentials

You can use one of the following methods to use different credentials to call different API operations in your application:

Use multiple Credentials clients

Initialize multiple Credentials clients to pass different credentials to different request clients.

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

public class DemoTest {
    public static void main(String[] args) throws Exception{
        Config credentialConfig1 = new Config();
        credentialConfig1.setType("access_key");
        credentialConfig1.setAccessKeyId("<ALIBABA_CLOUD_ACCESS_KEY_ID>");
        credentialConfig1.setAccessKeySecret("<ALIBABA_CLOUD_ACCESS_KEY_SECRET>");
        Client credentialClient1 = new Client(credentialConfig1);
      
        Config credentialConfig2 = new Config();
        credentialConfig2.setType("access_key");
        credentialConfig2.setAccessKeyId("<ALIBABA_CLOUD_ACCESS_KEY_ID>");
        credentialConfig2.setAccessKeySecret("<ALIBABA_CLOUD_ACCESS_KEY_SECRET>");
        Client credentialClient2 = new Client(credentialConfig2);
    }
}

Use the AuthUtils class

If you initialize a Credentials client by using the credential information recorded in a configuration file, you can use the AuthUtils.setClientType method to switch between different credentials.

[default]
enable=true
type=access_key
access_key_id=<ALIBABA_CLOUD_ACCESS_KEY_ID>
access_key_secret=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>

[client1]
enable=true
type=sts
access_key_id=<ALIBABA_CLOUD_ACCESS_KEY_ID>
access_key_secret=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>
security_token=<security_token>

[client2]
enable=true
type=ecs_ram_role
role_name=<ecs_ram_role_name>

Sample code:

import com.aliyun.credentials.utils.AuthUtils;

public class Sample {
    public static void main(String[] args) {
        // If you do not specify the clientType property of the AuthUtils class, default is used. 
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
        // Switch to the client1 credential.
        AuthUtils.setClientType("client1");
        com.aliyun.credentials.Client credentialClient1 = new com.aliyun.credentials.Client();
        // Switch to the client2 credential.
        AuthUtils.setClientType("client2");
        com.aliyun.credentials.Client credentialClient2 = new com.aliyun.credentials.Client();
    }
}

Call example

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for Java.

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 defaultCredentialClient = new com.aliyun.credentials.Client();
        /* Use client1 in the configuration file to initialize a Credentials client. */
        com.aliyun.credentials.utils.AuthUtils.setClientType("client1");
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();

        Config ecsConfig = new Config();
        // Specify the endpoint of the cloud service. 
        ecsConfig.setEndpoint("ecs.aliyuncs.com");
        // Use the SDK Credentials package to configure a credential. 
        ecsConfig.setCredential(defaultCredentialClient);
        // Initialize the ECS SDK client. 
        Client ecsClient = new Client(ecsConfig);
        // Initialize the request to call the DescribeRegions operation. 
        DescribeRegionsRequest describeRegionsRequest = new DescribeRegionsRequest();
        // Initialize the runtime configurations. 
        RuntimeOptions runtime = new RuntimeOptions();
        // Call the DescribeRegions operation and obtain a response. 
        DescribeRegionsResponse response = ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime);
        System.out.println(response.body.toMap());
    }
}

References