All Products
Search
Document Center

Alibaba Cloud SDK:Credentials

Last Updated:Sep 06, 2022

This topic describes how to configure credentials in Alibaba Cloud Classic SDK for Java.

If you use an AccessKey pair as an access credential, you must configure the credential when you initialize the client. This topic provides sample code.

Notice

Keep the code that contains your AccessKey pair confidential. For example, do not commit the code to public GitHub projects. If you commit the code, your Alibaba Cloud account may be compromised.

Use an AccessKey pair and an STS token

The following sample code shows how to use DefaultProfile to configure credentials:

import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.ecs.model.v20140526.*;
public class Main {
    public static void main(String[] args) {
        // Create a DefaultAcsClient instance and initialize the instance.
        DefaultProfile profile = DefaultProfile.getProfile(
            "<your-region-id>",          // The ID of the region.
            "<your-access-key-id>",      // The AccessKey ID of the Resource Access Management (RAM) user.
            "<your-access-key-secret>"); // The AccessKey secret of the RAM user.

        /** Use a Security Token Service (STS) token to configure a credential. Note: If you use an STS token as the access credential, you must periodically update your STS token. 
        DefaultProfile profile = DefaultProfile.getProfile(
            "<your-region-id>",          // The ID of the region.
            "<your-access-key-id>",      // The AccessKey ID that starts with STS.
            "<your-access-key-secret>",  // The AccessKey secret of the RAM user.
            "<your-sts-token>");         // STS Token
        **/
        
        IAcsClient client = new DefaultAcsClient(profile);
        // Create an API request and set the request parameters.
        DescribeInstancesRequest request = new DescribeInstancesRequest();
        request.setPageSize(10);
        // Send the request and handle the response or exception.
        DescribeInstancesResponse response;
        try {
            response = client.getAcsResponse(request);
            for (DescribeInstancesResponse.Instance instance:response.getInstances()) {+
                System.out.println(instance.getPublicIpAddress());
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}

You can also use SDK Credentials and CredentialsProvider to configure credentials.

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.BasicCredentials;
import com.aliyuncs.auth.STSAssumeRoleSessionCredentialsProvider;
import com.aliyuncs.ecs.model.v20140526.DescribeInstancesRequest;
import com.aliyuncs.ecs.model.v20140526.DescribeInstancesResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
public class UseRoleArnSample {
    public static void main(String[] args) {
        DefaultProfile profile = DefaultProfile.getProfile("<your-region-id>");
        BasicCredentials basicCredentials = new BasicCredentials(
            "<your-access-key-id>",
            "<your-access-key-secret>"
        );
        STSAssumeRoleSessionCredentialsProvider provider = new STSAssumeRoleSessionCredentialsProvider(
            basicCredentials,
            "<your-role-arn>",
            profile
        );
        // Use an AccessKey pair.
        DescribeInstancesRequest request = new DescribeInstancesRequest();
        /** Use an STS token.
        DefaultAcsClient client = new DefaultAcsClient(profile, provider);
        **/
        DescribeInstancesRequest request = new DescribeInstancesRequest();
        try {
            DescribeInstancesResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
        } catch (ClientException e) {
            System.err.println(e.toString());
        }
    }
}

Configure a RAM role to access ECS instances without using AccessKey pairs

To deploy applications in a secure and convenient manner, the Classic SDK allows you to use the RAM role of an Elastic Computer Service (ECS) instance to obtain a temporary authorization token. You can use the token to access the resources that are available for the RAM role of the ECS instance. For more information, see the Step 5 section in Use an instance RAM role by calling API operations. Then, the applications that are deployed on the ECS instance can access OpenAPI Explorer without using AccessKey pairs. After you configure credentials in the Classic SDK, the Classic SDK can have the permissions of the ECS RAM role.

Notice

Make sure that a RAM role is attached to an ECS instance.

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.InstanceProfileCredentialsProvider;
import com.aliyuncs.ecs.model.v20140526.DescribeInstancesRequest;
import com.aliyuncs.ecs.model.v20140526.DescribeInstancesResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
public class NoAKAccessSample {
    public static void main(String[] args) {
        DefaultProfile profile = DefaultProfile.getProfile("<your-region-id>");
        InstanceProfileCredentialsProvider provider = new InstanceProfileCredentialsProvider(
            "<your-role-name>"
        );
        DefaultAcsClient client = new DefaultAcsClient(profile, provider);
        DescribeInstancesRequest request = new DescribeInstancesRequest();
        try {
            DescribeInstancesResponse response = client.getAcsResponse(request);
        } catch (ClientException e) {
            System.err.println(e.toString());
        }
    }
}

If you specify a non-null value for the ALIBABA_CLOUD_ECS_METADATA environment variable, the provider chain uses the value of the environment variable as the role name, and then sends a request to http://100.100.100.200/latest/meta-data/ram/security-credentials/ to obtain temporary security credentials without other settings.

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.ecs.model.v20140526.*;
public class Main {
    public static void main(String[] args) {
        IAcsClient client = new DefaultAcsClient("your-region-id");
        // Create an API request and set the request parameters.
        DescribeInstancesRequest request = new DescribeInstancesRequest();
        request.setPageSize(10);
        // Send the request and handle the response or exception.
        DescribeInstancesResponse response;
        try {
            response = client.getAcsResponse(request);
            for (DescribeInstancesResponse.Instance instance:response.getInstances()) {
                System.out.println(instance.getPublicIpAddress());
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}

Use a bearer token

Only Cloud Call Center (CCC) allows you to configure a bearer token as an access credential in the Classic SDK.

package com.aliyun.sample;

import com.aliyuncs.auth.BearerTokenCredentials;
import com.aliyuncs.ccc.model.v20200701.ListPhoneNumbersRequest;
import com.aliyuncs.ccc.model.v20200701.ListPhoneNumbersResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;

public class Test {
    public static void main(String[] args) {
        // Create a DefaultAcsClient instance and initialize the instance.
        DefaultProfile profile = DefaultProfile.getProfile("<your-region-id>");// The ID of the region.
        BearerTokenCredentials bearerTokenCredential = new BearerTokenCredentials("<your-bearer-token>");
        DefaultAcsClient client = new DefaultAcsClient(profile,bearerTokenCredential);
        // Create an API request and set the request parameters.
        ListPhoneNumbersRequest request = new ListPhoneNumbersRequest();
        request.setInstanceId("yourId");
        // Send the request and handle the response or exception.
        ListPhoneNumbersResponse response;
        try{
            response = client.getAcsResponse(request);
        // The logic.
        } catch(ServerException e) {
            e.printStackTrace();
        } catch(ClientException e) {
            e.printStackTrace();
        }
    }
}

Use the default credential provider chain

The default provider chain searches for access credentials and uses the identified credentials in the following order:

1. System properties

The provider chain searches for credentials in system properties. If you specify non-null values for the environment variables alibabacloud.accessKeyId and alibabacloud.accessKeyIdSecret, the provider chain uses the environment variables to create default credentials.

2. Environmental credentials

The provider chain searches for credentials in environment variables. If you specify non-null values for the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, the provider chain uses the environment variables to create default credentials.

3. Configuration file

If the default credential file is stored in the home directory of the user, the provider chain automatically creates a credential based on the specified type and name. The path for the default credential file is ~/.alibabacloud/credentials. In Windows, the path is C:\Users\USER_NAME\.alibabacloud\credentials. If the default credential file does not exist, an exception is thrown when the system fails to parse a credential. The name of a configuration is in lowercase. The configuration file is stored outside projects and cannot be committed to public GitHub projects. Therefore, the configuration file can be used by different projects and tools at the same time. You can configure the ALIBABA_CLOUD_CREDENTIALS_FILE environment variable to change the path of the default credential file. If you do not specify a value for the ALIBABA_CLOUD_CREDENTIALS_FILE environment variable, the default configuration is used. You can also configure the ALIBABA_CLOUD_PROFILE environment variable to specify a configuration.

[default]                          # The configuration named default.
enable = true                      # The configuration is enabled. By default, the configuration is not enabled if this parameter is not specified.
type = access_key                  # The authentication is based on AccessKey pairs.
access_key_id = foo                # Key
access_key_secret = bar            # Secret

[client1]                          # The configuration named client1.
type = ecs_ram_role                # The authentication is based on ECS instance RAM roles.
role_name = EcsRamRoleTest         # Role Name

[client3]                          # The configuration named client2.
enable = false                     # The configuration is not enabled.
type = ram_role_arn                # The authentication is based on RAM Role ARNs.
region_id = cn-test                # Obtain the region of the session.
policy = test # Optional. Specify permissions.
access_key_id = foo
access_key_secret = bar
role_arn = role_arn
role_session_name = session_name   # Optional.

[client3]                          # The configuration named client3.
type = rsa_key_pair                # The authentication is based on RSA key pairs.
public_key_id = publicKeyId        # Public Key ID
private_key_file = /your/pk.pem    # The private key file.