All Products
Search
Document Center

Alibaba Cloud SDK:Request syntax and signature method V3

Last Updated:Jun 18, 2024

This topic describes the request syntax and signature method V3. This version uses common request headers to pass the required parameters of API operations, which shields the differences between different API styles. This allows you to use the same signature method for different API styles and call Alibaba Cloud API operations in a more standard and easier way. This topic helps you understand and use the request syntax and signature method V3 of Alibaba Cloud SDKs. This topic also describes how to construct a canonicalized HTTP request and how to use a correct signature algorithm to verify the identity of a request sender. This ensures the integrity and security of the transmitted data. You can read this topic to generate a signature for an Alibaba Cloud API request.

HTTP request syntax

The following table describes the components of an Alibaba Cloud API request.

Component

Required

Description

Example

Protocol

Yes

The protocol that is used to send the API request. You can read the API reference of each Alibaba Cloud service to obtain information about the protocol that is used. You can send a request over HTTP or HTTPS. To ensure data security, we recommend that you send requests over HTTPS. Valid values: https:// and http://.

https://

Endpoint

Yes

The endpoint of the Alibaba Cloud service API. Topics that list the endpoints of each Alibaba Cloud service are available. You can view the endpoints of a service in different regions in these topics.

cs.aliyuncs.com

resource_URI_parameters

Yes

The identifier of the resource that you want to access, including the resource path and the request parameters whose parameter location is path or query.

/clusters/{cluster_id}/triggers

RequestHeader

Yes

The request headers. In most cases, information such as the API version number, endpoint, and authentication information is included. For more information, see the "Request headers" section of this topic.

x-acs-action

RequestBody

Yes

The operation-specific parameters in the request body. For more information, visit OpenAPI Explorer.

cluster_id

HTTPMethod

Yes

The HTTP method that is used to send the request. Valid values: PUT, POST, GET, and DELETE.

POST

Request headers

The following table describes the request headers of an Alibaba Cloud API request.

Header

Type

Required

Description

Example

x-acs-action

String

Yes

The operation that you want to perform. You can search for the API operation that you want to call in OpenAPI Explorer.

RunInstances

x-acs-version

String

Yes

The version number of the API. You can view the API version of the service that you want to access in OpenAPI Explorer.

2014-05-26

Authorization

String

Yes if the request is non-anonymous

The authentication information that is used to verify the validity of the request. Format: Authorization: SignatureAlgorithm Credential=AccessKeyId,SignedHeaders=SignedHeaders,Signature=Signature. SignatureAlgorithm: the encryption method of the signature string. Set the value to ACS3-HMAC-SHA256.

Credential: the AccessKey ID that is provided by Alibaba Cloud. You can view your AccessKey ID in the Resource Access Management (RAM) console. For more information about how to create an AccessKey pair, see Obtain an AccessKey pair. SignedHeaders: the names of the request headers that are used for signature calculation. Note: All common request headers except the Authorization header must be used for signature calculation.

Signature: the signature string of the request. For more information, see the "Signature method" section of this topic.

ACS3-HMAC-SHA256 Credential=YourAccessKeyId,SignedHeaders=host;x-acs-action;x-acs-content-sha256;x-acs-date;x-acs-signature-nonce;x-acs-version,Signature=e521358f7776c97df52e6b2891a8bc73026794a071b50c3323388c4e0df64804

x-acs-signature-nonce

String

No

A unique and random number that is used to prevent replay attacks. We recommend that you use different numbers for different requests.

d410180a5abf7fe235dd9b74aca91fc0

x-acs-date

String

Yes

The timestamp of the request. Specify the time in the ISO 8601 standard in the yyyy-MM-ddTHH:mm:ssZ format. The time must be in UTC. Example: 2018-01-01T12:00:00Z. The timestamp must be within 15 minutes before the request is sent.

2023-10-26T09:01:01Z

host

String

Yes

The endpoint of the Alibaba Cloud service API. For more information, see the HTTP request syntax section of this topic.

ecs.cn-shanghai.aliyuncs.com

x-acs-content-sha256

String

Yes

The hash value of the request body. The hash value is encoded in Base16. The value of this header is the same as that of the HashedRequestPayload parameter.

e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

x-acs-security-token

String

Yes if Security Token Service (STS) is used for authentication

The STS token. Set this header to the value of the SecurityToken parameter in the response of the AssumeRole operation.

API request construction

A complete API request consists of the following parts:

HTTPMethod /resource_URI_parameters
RequestHeader
RequestBody

Request parameters consist of common request headers and operation-specific parameters. The common request headers contain information such as the API version number and authentication information.

  • HTTPMethod: the HTTP method that is used to send the request. Valid values: PUT, POST, GET, and DELETE. For more information, see the HTTP request syntax section of this topic.

  • resource_URI_parameters: the identifier of the resource that you want to access. Example: /cluster. For more information, see the HTTP request syntax section of this topic.

  • RequestHeader: the request headers. In most cases, information such as the API version number, endpoint, and authentication information is included. For more information, see the HTTP request syntax section of this topic.

  • RequestBody: the operation-specific parameters in the request body. For more information, see the HTTP request syntax section of this topic.

Sample request to call the RunInstances operation:

POST /?ImageId=win2019_1809_x64_dtc_zh-cn_40G_alibase_20230811.vhd&RegionId=cn-shanghai HTTP/1.1
Authorization: ACS3-HMAC-SHA256 Credential=YourAccessKeyId,SignedHeaders=host;x-acs-action;x-acs-content-sha256;x-acs-date;x-acs-signature-nonce;x-acs-version,Signature=e521358f7776c97df52e6b2891a8bc73026794a071b50c3323388c4e0df64804
x-acs-action: RunInstances
host: ecs.cn-shanghai.aliyuncs.com
x-acs-date: 2023-10-26T09:01:01Z
x-acs-version: 2014-05-26
x-acs-content-sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
x-acs-signature-nonce: d410180a5abf7fe235dd9b74aca91fc0
user-agent: AlibabaCloud (Mac OS X; x86_64) Java/1.8.0_352-b08 tea-util/0.2.6 TeaDSL/1
accept: application/json

Encoding

Requests and responses are encoded in UTF-8.

View API information

Go to the Alibaba Cloud API Documentation page and select a cloud service.

  1. In the left-side pane, click Metadata below the cloud service name. On the page that appears, find the info.style parameter to view the API style supported by the cloud service, such as remote procedure call (RPC) or resource-oriented architecture (ROA).

    image

    image

    Note

    The metadata displayed on the page contains all API information of the cloud service. If you want to view the metadata of an API operation, go to Step 2.

  2. Select the API operation that you want to call and click Metadata in the upper-right corner of the page.

    image

    The metadata of an API operation defines the network protocols, request methods, parameters, and parameter locations supported by the API operation. As shown in the following figure, the metadata of the RunInstances operation contains the following information:

    • Supported network protocols: HTTP and HTTPS. We recommend that you use HTTPS.

    • Supported request methods: GET and POST. You can use the two request methods to obtain the same response. However, if you use the GET method, a request packet can be up to 32 KB in size. We recommend that you use the POST method.

    • Supported parameters include RegionId and ImageId. The parameter location is query, which indicates that these parameters are concatenated and placed after the request URL. Example: https://ecs.cn-beijing.aliyuncs.com/?ImageId=aliyun_2_1903_x64_20G_alibase_20231221.vhd&InstanceChargeType=PostPaid&InstanceType=ecs.e-c1m1.large&InternetChargeType=PayByTraffic&MinAmount=1&Password=test%401234&RegionId=cn-beijing&SecurityGroupId=sg-2zec0dm6qi66XXXXXXXX&SystemDisk.Category=cloud_essd&SystemDisk.Size=40&VSwitchId=vsw-2ze3aagwn397gXXXXXXXX.

    image

    Note

    Other content of the metadata has no impact on signature calculation. For more information about the metadata, see Guidelines for use.

Signature method

You must sign all API requests to ensure security. Alibaba Cloud uses the request signature to verify the identity of the API caller. Each API request must contain a signature, regardless of whether the request is sent over HTTP or HTTPS. This section describes how to sign API requests.

For each HTTP or HTTPS request, Alibaba Cloud uses the request signature to verify the identity of the API caller. You can perform the following steps to sign a request:

Step 1: Construct a canonicalized request

To use an AccessKey pair to calculate or verify a signature, you must construct a canonicalized request. The client and API gateway must use the same request specifications so that they can obtain the same signature string for an HTTP request to complete identity verification.

Construct a canonicalized request based on the following pseudocode:

CanonicalRequest =
  HTTPRequestMethod + '\n' +    // The HTTP request method in uppercase letters.
  CanonicalURI + '\n' +         // The canonicalized uniform resource identifier (URI).
  CanonicalQueryString + '\n' + // The canonicalized query string.
  CanonicalHeaders + '\n' +     // The canonicalized request headers.
  SignedHeaders + '\n' +        // The request headers that are used for signature calculation.
  HashedRequestPayload			
  • HTTPRequestMethod

    The HTTP request method in uppercase letters, such as GET or POST.

  • CanonicalURI

    The encoded resource path in the URL. The resource path is the part between the endpoint and the query string. The path includes the forward slash (/) that follows the endpoint but excludes the question mark (?) that precedes the query string. You must use a canonicalized URI for signature calculation. To construct a canonicalized URI, encode the strings separated by forward slashes (/) in UTF-8 based on RFC 3986. Encoding rules:

    • Letters, digits, hyphens (-), underscores (_), periods (.), and tildes (~) do not need to be encoded.

    • Other characters must be percent-encoded in the following format: % + ASCII code of the characters in hexadecimal notation. For example, double quotation marks (") are encoded as %22.

    • Spaces must be encoded as %20 instead of plus signs (+). Asterisks (*) are encoded as %2A. %7E is replaced by tildes (~).

      If you use java.net.URLEncoder in the Java standard library, encode the strings based on the standard library. In the encoded strings, replace plus signs (+) with %20, asterisks (*) with %2A, and %7E with tildes (~). This way, you can obtain encoded strings that match the preceding encoding rules.

    Important

    If the API style is RPC, use a forward slash (/) as the value of the CanonicalURI parameter.

    If the API style is ROA, encode the value of the path parameter in the metadata and use the encoded value as the value of the CanonicalURI parameter. Example: /api/v1/clusters.

  • CanonicalQueryString

    The canonicalized query string. You can perform the following steps to construct the canonicalized query string:

    1. Sort the parameters in the query string by parameter name in alphabetical order. For parameters with the same name, sort the parameters by parameter value in alphabetical order.

    2. Encode the parameter names and values in UTF-8 based on RFC 3986. The encoding rules are the same as those used to construct the canonicalized URI.

    3. Use an equal sign (=) to concatenate the encoded name and value of each parameter. For a parameter without a value, use an empty string as the parameter value.

    4. Use ampersands (&) to concatenate the encoded parameters in the order obtained in the previous step.

    Important

    If the query string is empty, use an empty string as the canonicalized query string.

  • CanonicalHeaders

    The canonicalized request headers. You must add non-standard HTTP request headers whose names are prefixed with x-acs-, host, or content-type as canonicalized request headers. You can perform the following steps to construct canonicalized request headers:

    1. Convert the names of all headers that are used for signature calculation to lowercase letters.

    2. Sort all headers by header name in alphabetical order.

    3. Remove the spaces before and after the value of each header. If a header has multiple values, remove the spaces before and after each value, sort the values in alphabetical order, and then use commas (,) to concatenate the values.

    4. Use a colon (:) to concatenate the name and value of each header obtained in the preceding steps and add a line break at the end to construct a canonicalized request header.

    5. If no headers are used for signature calculation, use an empty string as the canonicalized request headers.

    Important

    All common request headers except the Authorization header must be used for signature calculation.

  • SignedHeaders

    The request headers that are used for signature calculation. This parameter contains the same headers as those in the CanonicalHeaders parameter. You can perform the following steps to construct signed headers:

    • Convert the names of headers in the CanonicalHeaders parameter to lowercase letters.

    • Use semicolons (;) to concatenate all the headers by lowercase header name in alphabetical order. Example: content-type;host;x-acs-date.

    • Pseudocode:

      CanonicalHeaderEntry = Lowercase(HeaderName) + ':' + Trim(HeaderValue) + '\n'
      
      CanonicalHeaders = 
          CanonicalHeaderEntry0 + CanonicalHeaderEntry1 + ... + CanonicalHeaderEntryN
  • HashedRequestPayload

    The hash value of the request body. If the request body is empty, use an empty string as the value of the RequestPayload parameter. Otherwise, the value of the RequestPayload parameter is the JSON string that corresponds to the request body. Use a hash algorithm to calculate the hash value for the value of the RequestPayload parameter and obtain the value of the HashedRequestPayload parameter. The following pseudocode shows how to generate the hash value: HashedRequestPayload = HexEncode(Hash(RequestPayload)).

    • Hash() indicates the hash algorithm. Only the SHA-256 algorithm is supported. For example, if the encryption method of the signature string is ACS3-HMAC-SHA256, you must use SHA-256 as the hash algorithm.

    • HexEncode() encodes the hash value in Base16. This function returns an encoded hash value in the hexadecimal format in lowercase letters.

    Table 1: Mappings among the encryption methods of the signature string, signature calculation algorithms, and hash algorithms

    Encryption method of the signature string (SignatureAlgorithm)

    Hash algorithm used to process RequestPayload and CanonicalRequest (Hash)

    Algorithm for signature calculation

    (SignatureMethod)

    ACS3-HMAC-SHA256

    SHA256

    HMAC-SHA256

Step 2: Construct a string-to-sign

Construct a string-to-sign based on the following pseudocode:

StringToSign =
    SignatureAlgorithm + '\n' +
    HashedCanonicalRequest
  • SignatureAlgorithm

    The encryption method of the signature string. Only ACS3-HMAC-SHA256 is supported. The MD5- or SHA1-based algorithms are no longer supported.

  • HashedCanonicalRequest

    The hash value of the canonicalized request. The following pseudocode shows how to generate the hash value:

    HashedCanonicalRequest = HexEncode(Hash(CanonicalRequest))
  1. Calculate the hash value of the canonicalized request that is obtained in Step 1. Select a hash algorithm based on the encryption method of the signature string, which is specified by the SignatureAlgorithm parameter. For more information, see Table 1 of this topic. Only ACS3-HMAC-SHA256 can be used as the encryption method. In this case, you must use SHA-256 as the hash algorithm.

  2. Encode the hash value that is obtained in the previous step in Base16.

Step 3: Calculate the signature string

Calculate the signature string based on the following pseudocode:

Signature = HexEncode(SignatureMethod(Secret, StringToSign))
  • StringToSign: the string-to-sign that is constructed in Step 2. The value is encoded in UTF-8.

  • SignatureMethod: the algorithm for signature calculation. Select an algorithm based on the encryption method of the signature string, which is specified by the SignatureAlgorithm parameter. For more information, see Table 1 of this topic.

  • Secret: the AccessKey secret provided by Alibaba Cloud. The value is in the binary format.

  • HexEncode: the function that is used to encode values in Base16.

Step 4: Add the signature string to the request

After you obtain the signature string, specify the Authorization header in the request in the following format: Authorization:<SignatureAlgorithm> Credential=<AccessKeyId>,SignedHeaders=<SignedHeaders>,Signature=<Signature>. Example:

Authorization:ACS3-HMAC-SHA256 Credential=YourAccessKeyId,SignedHeaders=content-type;host;x-acs-timestamp,Signature=6b595d672d79c15b18edb4ccfba6789a24a6f2b82c400e03162d9279b08555d7

Signature calculation examples

Note
  1. To help you understand the preceding signature method, this topic provides the following sample code to completely implement the signature method in mainstream programming languages. The following sample code is provided only to help you understand the signature method and is not globally applicable. Alibaba Cloud provides SDKs for multiple programming languages and development frameworks. We recommend that you use Alibaba Cloud SDKs to initiate API requests and automatically generate signatures for the requests. You can develop applications on Alibaba Cloud without the need to manually calculate a signature.

  2. Before you sign an API request, you must view the API information to obtain information such as the request methods, request parameters, and parameter locations of the API operation that you want to call.

Java

To use the signature method in Java, you must add the following Maven dependencies to the pom.xml file:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>
<dependency>
     <groupId>com.google.code.gson</groupId>
     <artifactId>gson</artifactId>
     <version>2.9.0</version>
 </dependency>
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * The signature demo.
 */
public class SignatureDemo {

    /**
     * The tool that is used to format dates. The tool can format a DATETIME string into a value in the yyyy-MM-dd'T'HH:mm:ss'Z format. 
     */
    private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

    private static class Request {
        // The HTTP request method.
        private final String httpMethod;
        // The canonicalized URI. If the resource path is empty, use a forward slash (/) as the value of the CanonicalURI parameter.
        private final String canonicalUri;
        // The endpoint.
        private final String host;
        // The operation that you want to perform.
        private final String xAcsAction;
        // The version number of the API.
        private final String xAcsVersion;
        // The request headers.
        TreeMap<String, Object> headers = new TreeMap<>();
        // The request parameters whose parameter location is body. These parameters are the operation-specific parameters in the request body. The value must be a JSON string.
        String body;
        // The request parameters whose parameter location is query. These parameters are sorted by parameter name in alphabetical order and placed in the request URL.
        TreeMap<String, Object> queryParam = new TreeMap<>();

        public Request(String httpMethod, String canonicalUri, String host, String xAcsAction, String xAcsVersion) {
            this.httpMethod = httpMethod;
            this.canonicalUri = canonicalUri;
            this.host = host;
            this.xAcsAction = xAcsAction;
            this.xAcsVersion = xAcsVersion;
            initBuilder();
        }

        // The request headers.
        private void initBuilder() {
            headers.put("host", host);
            headers.put("x-acs-action", xAcsAction);
            headers.put("x-acs-version", xAcsVersion);
            SDF.setTimeZone(new SimpleTimeZone(0, "GMT")); // Set the time zone for date formatting to GMT.
            headers.put("x-acs-date", SDF.format(new Date()));
            headers.put("x-acs-signature-nonce", UUID.randomUUID().toString());
        }
    }

    /**
     * In this example, the AccessKey ID and AccessKey secret are obtained by using environment variables. 
     */
    private final static String ACCESS_KEY_ID = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    private final static String ACCESS_KEY_SECRET = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");


    /**
     * The signature algorithm.
     */
    private static final String ALGORITHM = "ACS3-HMAC-SHA256";

    /**
     * The main function is used to show how to send an API request by using Alibaba Cloud SDK for Java. 
     * Construct a request based on the specified parameters and perform signature authentication. 
     */
    public static void main(String[] args) {
        // Construct a request for an RPC API operation.
        String httpMethod = "POST"; // The HTTP request method.
        String canonicalUri = "/";
        String host = "ecs.cn-beijing.aliyuncs.com";  // The endpoint.
        String xAcsAction = "DescribeInstances";  // The operation that you want to perform.
        String xAcsVersion = "2014-05-26"; // The version number of the API.
        Request request = new Request(httpMethod, canonicalUri, host, xAcsAction, xAcsVersion);

        // The request parameters. Sort the parameters by parameter name in alphabetical order. For parameters with the same name, sort the parameters by parameter value in alphabetical order. 
        request.queryParam.put("RegionId", "cn-beijing");
        request.queryParam.put("VpcId", "vpc-2zeo42r27y4opXXXXXXXX");


/*         // Construct a POST request for an ROA API operation.
        String httpMethod = "POST";
        String canonicalUri = "/clusters";
        String host = "cs.cn-beijing.aliyuncs.com"; // The endpoint.
        String xAcsAction= "CreateCluster"; // The operation that you want to perform.
        String xAcsVersion=  "2015-12-15"; // The version number of the API.
        Request request = new Request(httpMethod, canonicalUri, host, xAcsAction, xAcsVersion);

        // The request body. Use Gson to convert the request body into a JSON string.
        TreeMap<String, Object> body = new TreeMap<>();
        body.put("name", "testDemo");
        body.put("region_id", "cn-beijing");
        body.put("cluster_type", "Kubernetes");
        body.put("vpcid", "vpc-2zeo42r27y4opXXXXXXXX");
        body.put("service_cidr", "172.16.1.0/20");
        body.put("security_group_id", "sg-2zec0dm6qi66XXXXXXXX");
        Gson gson = (new GsonBuilder()).disableHtmlEscaping().create();
        request.body = gson.toJson(body);
        request.headers.put("content-type", "application/json; charset=utf-8");*/


/*        // Construct a GET request for an ROA API operation.
        String httpMethod = "GET";
        // The canonicalized URI. If the resource path is empty, use a forward slash (/) as the value of the CanonicalURI parameter.
        String canonicalUri = "/api/v1/clusters";
        String host= "cs.cn-beijing.aliyuncs.com"; // The endpoint.
        String xAcsAction=  "DescribeClustersV1"; // The operation that you want to perform.
        String xAcsVersion= "2015-12-15"; // The version number of the API.
        Request request = new Request(httpMethod, canonicalUri, host, xAcsAction, xAcsVersion);

        request.queryParam.put("cluster_id", "cd4b2c37e17184bc5a81a928eXXXXXXXX");
        request.queryParam.put("cluster_type", "Kubernetes");
        request.queryParam.put("region_id", "cn-beijing");
        request.queryParam.put("name", "testDemo");
        request.queryParam.put("page_size", 10);
        request.queryParam.put("page_number", 1);*/

        // Sign the request.
        getAuthorization(request);
        // Call the API operation.
        callApi(request);
    }

    private static void callApi(Request request) {
        try {
            // Send the request by using HttpClient.
            String url = "https://" + request.host + request.canonicalUri;
            URIBuilder uriBuilder = new URIBuilder(url);
            // Specify request parameters.
            for (Map.Entry<String, Object> entry : request.queryParam.entrySet()) {
                uriBuilder.addParameter(entry.getKey(), String.valueOf(entry.getValue()));
            }
            HttpUriRequest httpRequest;
            switch (request.httpMethod) {
                case "GET":
                    httpRequest = new HttpGet(uriBuilder.build());
                    break;
                case "POST":
                    HttpPost httpPost = new HttpPost(uriBuilder.build());
                    if (request.body != null) {
                        StringEntity postEntity = new StringEntity(request.body);
                        httpPost.setEntity(postEntity);
                    }
                    httpRequest = httpPost;
                    break;
                case "DELETE":
                    httpRequest = new HttpDelete(uriBuilder.build());
                    break;
                case "PUT":
                    HttpPut httpPut = new HttpPut(uriBuilder.build());
                    if (request.body != null) {
                        StringEntity putEntity = new StringEntity(request.body);
                        httpPut.setEntity(putEntity);
                    }
                    httpRequest = httpPut;
                    break;
                default:
                    System.out.println("Unsupported HTTP method: " + request.body);
                    throw new IllegalArgumentException("Unsupported HTTP method");
            }

            // Specify HTTP request headers.
            for (Map.Entry<String, Object> entry : request.headers.entrySet()) {
                httpRequest.addHeader(entry.getKey(), String.valueOf(entry.getValue()));
            }
            // Send the request.
            try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(httpRequest)) {
                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(result);
            } catch (IOException e) {
                // Handle errors.
                System.out.println("Failed to send request");
                e.printStackTrace();
            }
        } catch (URISyntaxException e) {
            // Handle errors.
            System.out.println("Invalid URI syntax");
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // Handle errors.
            System.out.println("UnsupportedEncodingException");
            e.printStackTrace();
        }
    }

    /**
     * This method is used to calculate and generate a signature string based on the specified HTTP request method, canonicalized URI, and query parameters. 
     */
    private static void getAuthorization(Request request) {
        try {
            // Step 1: Construct a canonicalized request.
            // The request parameters. If the query string is empty, use an empty string as the canonicalized query string.
            StringBuilder canonicalQueryString = new StringBuilder();
            request.queryParam.entrySet().stream().map(entry -> percentCode(entry.getKey()) + "=" + percentCode(String.valueOf(entry.getValue()))).forEachOrdered(queryPart -> {
                // If the canonicalized query string is not empty, use ampersands (&) to concatenate more request parameters.
                if (canonicalQueryString.length() > 0) {
                    canonicalQueryString.append("&");
                }
                canonicalQueryString.append(queryPart);
            });

            // The request body. If the request body is empty, such as in a GET request, use an empty string as the value of the RequestPayload parameter.
            String requestPayload = "";
            if (request.body != null) {
                requestPayload = request.body;
            }

            // Calculate the hash value of the request body.
            String hashedRequestPayload = sha256Hex(requestPayload);
            request.headers.put("x-acs-content-sha256", hashedRequestPayload);
            // Construct request headers. Concatenate multiple canonicalized request headers by lowercase header name in alphabetical order.
            StringBuilder canonicalHeaders = new StringBuilder();
            // The request headers that are used for signature calculation. Use semicolons (;) to concatenate all the headers by lowercase header name in alphabetical order.
            StringBuilder signedHeadersSb = new StringBuilder();
            request.headers.entrySet().stream().filter(entry -> entry.getKey().toLowerCase().startsWith("x-acs-") || entry.getKey().equalsIgnoreCase("host") || entry.getKey().equalsIgnoreCase("content-type")).sorted(Map.Entry.comparingByKey()).forEach(entry -> {
                String lowerKey = entry.getKey().toLowerCase();
                String value = String.valueOf(entry.getValue()).trim();
                canonicalHeaders.append(lowerKey).append(":").append(value).append("\n");
                signedHeadersSb.append(lowerKey).append(";");
            });
            String signedHeaders = signedHeadersSb.substring(0, signedHeadersSb.length() - 1);
            String canonicalRequest = request.httpMethod + "\n" + request.canonicalUri + "\n" + canonicalQueryString + "\n" + canonicalHeaders + "\n" + signedHeaders + "\n" + hashedRequestPayload;
            System.out.println("canonicalRequest=========>\n" + canonicalRequest);

            // Step 2: Construct a string-to-sign.
            String hashedCanonicalRequest = sha256Hex(canonicalRequest); // Calculate the hash value of the canonicalized request.
            String stringToSign = ALGORITHM + "\n" + hashedCanonicalRequest;
            System.out.println("stringToSign=========>\n" + stringToSign);

            // Step 3: Calculate the signature string.
            String signature = DatatypeConverter.printHexBinary(hmac256(ACCESS_KEY_SECRET.getBytes(StandardCharsets.UTF_8), stringToSign)).toLowerCase();
            System.out.println("signature=========>" + signature);

            // Step 4: Specify the Authorization header.
            String authorization = ALGORITHM + " " + "Credential=" + ACCESS_KEY_ID + ",SignedHeaders=" + signedHeaders + ",Signature=" + signature;
            System.out.println("authorization=========>" + authorization);
            request.headers.put("Authorization", authorization);
        } catch (Exception e) {
            // Handle errors.
            System.out.println("Failed to get authorization");
            e.printStackTrace();
        }
    }

    /**
     * Use the HMAC-SHA256 algorithm to generate a message authentication code (MAC). 
     *
     * @param key The key that is used to generate the MAC, which must be kept confidential. 
     * @param str The message to be authenticated. 
     * @return The MAC that is calculated by using the HMAC-SHA256 algorithm. 
     * @throws Exception The error that is reported when the MAC generator is initialized or the MAC is calculated. 
     */
    public static byte[] hmac256(byte[] key, String str) throws Exception {
        // Obtain the object on which the HMAC-SHA256 algorithm is implemented.
        Mac mac = Mac.getInstance("HmacSHA256");
        // Create a key standard to initialize the MAC generator.
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, mac.getAlgorithm());
        // Initialize the MAC generator.
        mac.init(secretKeySpec);
        // Calculate and return the MAC.
        return mac.doFinal(str.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * Calculate the hash value of the signature string by using the SHA-256 algorithm and return the hash value as a string in the hexadecimal format. 
     *
     * @param str The string to be calculated by using the SHA-256 algorithm. 
     * @return The string in the hexadecimal format in lowercase letters. 
     * @throws Exception The error that is reported when you obtain the object on which the SHA-256 algorithm is implemented. 
     */
    public static String sha256Hex(String str) throws Exception {
        // Obtain the object on which the SHA-256 algorithm is implemented.
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        // Calculate the hash value of the string by using the SHA-256 algorithm.
        byte[] d = md.digest(str.getBytes(StandardCharsets.UTF_8));
        // Convert the hash value to a string in the hexadecimal format in lowercase letters and return the string.
        return DatatypeConverter.printHexBinary(d).toLowerCase();
    }

    /**
     * Perform URL encoding on the specified string. 
     * Encode the string in UTF-8 and replace specific characters to comply with URL encoding specifications. 
     *
     * @param str The string to be URL-encoded. 
     * @return The URL-encoded string. Plus signs (+) are replaced by %20, asterisks (*) are replaced by %2A, and %7E is replaced by tildes (~). 
     */
    public static String percentCode(String str) {
        if (str == null) {
            throw new IllegalArgumentException("The specified string cannot be null.");
        }
        try {
            return URLEncoder.encode(str, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UTF-8 encoding is not supported.", e);
        }
    }
}

Python

You must manually install the pytz and requests libraries. Run the following commands on the terminal based on your Python version:

Python3

pip3 install pytz
pip3 install requests

Python2

pip install pytz
pip install requests
import hashlib
import hmac
import json
import os
import random
import string
import uuid
from collections import OrderedDict
from urllib.parse import urlencode, quote_plus

import requests
from datetime import datetime, timezone


class Request:
    def __init__(self, http_method, canonical_uri, host, x_acs_action, x_acs_version):
        self.http_method = http_method
        self.canonical_uri = canonical_uri
        self.host = host
        self.x_acs_action = x_acs_action
        self.x_acs_version = x_acs_version
        self.headers = self._init_headers()
        self.query_param = OrderedDict()
        self.body = None

    def _init_headers(self):
        headers = OrderedDict()
        headers['host'] = self.host
        headers['x-acs-action'] = self.x_acs_action
        headers['x-acs-version'] = self.x_acs_version
        utc_time = datetime.utcnow().replace(tzinfo=timezone.utc)
        headers['x-acs-date'] = utc_time.strftime('%Y-%m-%dT%H:%M:%SZ')
        headers['x-acs-signature-nonce'] = str(uuid.uuid4())
        return headers

    def sorted_query_params(self):
        # Sort query parameters by parameter name in alphabetical order and return the encoded string.
        sorted_query_params = sorted(self.query_param.items(), key=lambda item: item[0])
        self.query_param = {k: v for k, v in sorted_query_params}

    def sorted_headers(self):
        # Sort request headers by header name in alphabetical order and return the encoded string.
        sorted_headers = sorted(self.headers.items(), key=lambda item: item[0])
        self.headers = {k: v for k, v in sorted_headers}


# Obtain the AccessKey ID and AccessKey secret by using environment variables.
ACCESS_KEY_ID = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID')
ACCESS_KEY_SECRET = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET')

ALGORITHM = 'ACS3-HMAC-SHA256'


def get_authorization(request):
    try:
        # Step 1: Construct a canonicalized query string and calculate the hash value of the request body.
        canonical_query_string = '&'.join(
            f'{percent_code(quote_plus(k))}={percent_code(quote_plus(v))}' for k, v in request.query_param.items())
        hashed_request_payload = sha256_hex(request.body or '')
        request.headers['x-acs-content-sha256'] = hashed_request_payload
        request.sorted_headers()

        # Construct canonicalized request headers and signed headers.
        canonical_headers = '\n'.join(f'{k.lower()}:{v}' for k, v in request.headers.items() if
                                      k.lower().startswith('x-acs-') or k.lower() in ['host', 'content-type'])
        signed_headers = ';'.join(sorted(request.headers.keys(), key=lambda x: x.lower()))

        canonical_request = f'{request.http_method}\n{request.canonical_uri}\n{canonical_query_string}\n{canonical_headers}\n\n{signed_headers}\n{hashed_request_payload}'
        print(canonical_request)

        # Step 2: Construct a string-to-sign.
        hashed_canonical_request = sha256_hex(canonical_request)
        string_to_sign = f'{ALGORITHM}\n{hashed_canonical_request}'
        print(string_to_sign)

        # Step 3: Calculate the signature string.
        signature = hmac256(ACCESS_KEY_SECRET.encode('utf-8'), string_to_sign).hex().lower()
        print(signature)

        # Step 4: Specify the Authorization header.
        authorization = f'{ALGORITHM} Credential={ACCESS_KEY_ID},SignedHeaders={signed_headers},Signature={signature}'
        print(authorization)
        request.headers['Authorization'] = authorization
    except Exception as e:
        print("Failed to get authorization")
        print(e)


def hmac256(key, msg):
    return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()


def sha256_hex(s):
    return hashlib.sha256(s.encode('utf-8')).hexdigest()


def call_api(request):
    url = f'https://{request.host}{request.canonical_uri}'
    if request.query_param:
        url += '?' + urlencode(request.query_param, doseq=True, safe='*')
    headers = {k: v for k, v in request.headers.items()}
    if request.body:
        data = request.body
    else:
        data = None

    try:
        response = requests.request(method=request.http_method, url=url, headers=headers, data=data)
        response.raise_for_status()
        print(response.text)
    except requests.RequestException as e:
        print("Failed to send request")
        print(e)


def percent_code(encoded_str):
    return encoded_str.replace('+', '%20').replace('*', '%2A').replace('%7E', '~')


if __name__ == "__main__":
    # Construct a request for an RPC API operation.
    http_method = "POST"
    canonical_uri = "/"
    host = "ecs.cn-beijing.aliyuncs.com"
    x_acs_action = "DescribeInstances"
    x_acs_version = "2014-05-26"
    request = Request(http_method, canonical_uri, host, x_acs_action, x_acs_version)
    request.query_param['RegionId'] = 'cn-beijing'
    request.query_param['VpcId'] = 'vpc-2zeo42r27y4opXXXXXXXX'

    # Construct a POST request for an ROA API operation.
    # http_method = "POST"
    # canonical_uri = "/clusters"
    # host = "cs.cn-beijing.aliyuncs.com"
    # x_acs_action = "CreateCluster"
    # x_acs_version = "2015-12-15"
    # request = Request(http_method, canonical_uri, host, x_acs_action, x_acs_version)
    # body = OrderedDict()
    # body["name"] = "testDemo"
    # body["region_id"] = "cn-beijing"
    # body["cluster_type"] = "Kubernetes"
    # body["vpcid"] = "vpc-2zeo42r27y4opXXXXXXXX"
    # body["service_cidr"] = "172.16.1.0/20"
    # body["security_group_id"] = "sg-2zec0dm6qi66XXXXXXXX"
    #
    # request.body = json.dumps(body, separators=(',', ':'))
    # request.headers["content-type"] = "application/json; charset=utf-8"

    # Construct a GET request for an ROA API operation.
    # http_method = "GET"
    # canonical_uri = "/api/v1/clusters"
    # host = "cs.cn-beijing.aliyuncs.com"
    # x_acs_action = "DescribeClustersV1"
    # x_acs_version = "2015-12-15"
    # request = Request(http_method, canonical_uri, host, x_acs_action, x_acs_version)
    # request.query_param['page_size'] = '10'
    # request.query_param['page_number'] = '1'
    # request.query_param['cluster_id'] = 'cd4b2c37e17184bc5a81a928eXXXXXXXX'
    # request.query_param['cluster_type'] = 'Kubernetes'
    # request.query_param['region_id'] = 'cn-beijing'
    # request.query_param['name'] = 'testDemo'

    request.sorted_query_params()
    get_authorization(request)
    call_api(request)

Go

You must run the following commands on the terminal:

go get github.com/google/uuid
go get golang.org/x/exp/maps
package main

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"golang.org/x/exp/maps"
	"io"
	"os"
	"sort"

	"fmt"
	"net/http"
	"net/url"
	"strings"
	"time"

	"github.com/google/uuid"
)

type Request struct {
	httpMethod   string
	canonicalUri string
	host         string
	xAcsAction   string
	xAcsVersion  string
	headers      map[string]string
	body         string
	queryParam   map[string]string
}

func NewRequest(httpMethod, canonicalUri, host, xAcsAction, xAcsVersion string) *Request {
	req := &Request{
		httpMethod:   httpMethod,
		canonicalUri: canonicalUri,
		host:         host,
		xAcsAction:   xAcsAction,
		xAcsVersion:  xAcsVersion,
		headers:      make(map[string]string),
		queryParam:   make(map[string]string),
	}
	req.headers["host"] = host
	req.headers["x-acs-action"] = xAcsAction
	req.headers["x-acs-version"] = xAcsVersion
	req.headers["x-acs-date"] = time.Now().UTC().Format(time.RFC3339)
	req.headers["x-acs-signature-nonce"] = uuid.New().String()
	return req
}

var (
	AccessKeyId     = os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
	AccessKeySecret = os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
	ALGORITHM       = "ACS3-HMAC-SHA256"
)

func main() {
	// Construct a request for an RPC API operation.
	httpMethod := "POST"
	canonicalUri := "/"
	host := "ecs.cn-beijing.aliyuncs.com"
	xAcsAction := "DescribeInstances"
	xAcsVersion := "2014-05-26"
	req := NewRequest(httpMethod, canonicalUri, host, xAcsAction, xAcsVersion)
	req.queryParam["RegionId"] = "cn-beijing"
	req.queryParam["VpcId"] = "vpc-2zeo42r27y4opXXXXXXXX"

	/*	// Construct a POST request for an ROA API operation.
		httpMethod := "POST"
		canonicalUri := "/clusters"
		host := "cs.cn-beijing.aliyuncs.com"
		xAcsAction := "CreateCluster"
		xAcsVersion := "2015-12-15"
		req := NewRequest(httpMethod, canonicalUri, host, xAcsAction, xAcsVersion)
		body := make(map[string]string)
		body["name"] = "testDemo"
		body["region_id"] = "cn-beijing"
		body["cluster_type"] = "Kubernetes"
		body["vpcid"] = "vpc-2zeo42r27y4opXXXXXXXX"
		body["service_cidr"] = "172.16.1.0/20"
		body["security_group_id"] = "sg-2zec0dm6qi66XXXXXXXX"
		jsonBytes, err := json.Marshal(body)
		if err != nil {
			fmt.Println("Error marshaling to JSON:", err)
			return
		}
		req.body = string(jsonBytes)
		req.headers["content-type"] = "application/json; charset=utf-8"*/

	/*	// Construct a GET request for an ROA API operation.
		httpMethod := "GET"
		canonicalUri := "/api/v1/clusters"
		host := "cs.cn-beijing.aliyuncs.com"
		xAcsAction := "DescribeClustersV1"
		xAcsVersion := "2015-12-15"
		req := NewRequest(httpMethod, canonicalUri, host, xAcsAction, xAcsVersion)
		req.queryParam["page_size"] = "10"
		req.queryParam["page_number"] = "1"
		req.queryParam["cluster_id"] = "cd4b2c37e17184bc5a81a928eXXXXXXXX"
		req.queryParam["cluster_type"] = "Kubernetes"
		req.queryParam["region_id"] = "cn-beijing"
		req.queryParam["name"] = "testDemo"*/

	req.queryParam = sorted(req.queryParam)
	// Sign the request.
	getAuthorization(req)
	// Call the API operation.
	err := callAPI(req)
	if err != nil {
		println(err.Error())
	}
}

func sorted(obj map[string]string) map[string]string {
	keys := maps.Keys(obj)
	sort.Strings(keys)
	newObj := make(map[string]string)
	for _, k := range keys {
		newObj[k] = obj[k]
	}
	return newObj
}

func callAPI(req *Request) error {
	urlStr := "https://" + req.host + req.canonicalUri
	q := url.Values{}
	for k, v := range req.queryParam {
		q.Set(k, v)
	}
	urlStr += "?" + q.Encode()

	httpReq, err := http.NewRequest(req.httpMethod, urlStr, strings.NewReader(req.body))
	if err != nil {
		return err
	}

	for key, value := range req.headers {
		httpReq.Header.Set(key, value)
	}

	client := &http.Client{}
	resp, err := client.Do(httpReq)
	if err != nil {
		return err
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			return
		}
	}(resp.Body)
	var respBuffer bytes.Buffer
	_, err = io.Copy(&respBuffer, resp.Body)
	if err != nil {
		panic(err)
		return err
	}
	respBytes := respBuffer.Bytes()
	fmt.Println(string(respBytes))
	return nil
}

func getAuthorization(req *Request) {
	canonicalQueryString := ""
	for k, v := range req.queryParam {
		canonicalQueryString += percentCode(url.QueryEscape(k)) + "=" + percentCode(url.QueryEscape(v)) + "&"
	}
	canonicalQueryString = strings.TrimSuffix(canonicalQueryString, "&")

	hashedRequestPayload := sha256Hex(req.body)
	req.headers["x-acs-content-sha256"] = hashedRequestPayload

	canonicalHeaders := ""
	signedHeaders := ""
	HeadersKeys := maps.Keys(req.headers)
	sort.Strings(HeadersKeys)
	for _, k := range HeadersKeys {
		lowerKey := strings.ToLower(k)
		if lowerKey == "host" || strings.HasPrefix(lowerKey, "x-acs-") || lowerKey == "content-type" {
			canonicalHeaders += lowerKey + ":" + req.headers[k] + "\n"
			signedHeaders += lowerKey + ";"
		}
	}
	signedHeaders = strings.TrimSuffix(signedHeaders, ";")

	canonicalRequest := req.httpMethod + "\n" + req.canonicalUri + "\n" + canonicalQueryString + "\n" + canonicalHeaders + "\n" + signedHeaders + "\n" + hashedRequestPayload
	fmt.Printf("canonicalRequest========>\n%s\n", canonicalRequest)

	hashedCanonicalRequest := sha256Hex(canonicalRequest)
	stringToSign := ALGORITHM + "\n" + hashedCanonicalRequest
	fmt.Printf("stringToSign========>\n%s\n", stringToSign)

	byteData, err := hmac256([]byte(AccessKeySecret), stringToSign)
	if err != nil {
		fmt.Println(err)
	}
	signature := strings.ToLower(hex.EncodeToString(byteData))

	authorization := ALGORITHM + " Credential=" + AccessKeyId + ",SignedHeaders=" + signedHeaders + ",Signature=" + signature
	fmt.Printf("authorization========>%s\n", authorization)
	req.headers["Authorization"] = authorization
}

func hmac256(key []byte, toSignString string) ([]byte, error) {
	// Obtain the object on which the HMAC-SHA256 algorithm is implemented.
	h := hmac.New(sha256.New, key)
	// Construct a string-to-sign.
	_, err := h.Write([]byte(toSignString))
	if err != nil {
		return nil, err
	}
	// Calculate the hash value of the signature string and return the hash value.
	return h.Sum(nil), nil
}

func sha256Hex(str string) string {
	// Obtain the object on which the SHA-256 algorithm is implemented.
	hash := sha256.New()
	// Write the signature string to the hash function.
	_, _ = hash.Write([]byte(str))
	// Calculate the hash value of the signature string by using the SHA-256 algorithm and return the hash value as a string in the hexadecimal format in lowercase letters.
	hexString := hex.EncodeToString(hash.Sum(nil))

	return hexString
}

func percentCode(str string) string {
	// Replace specific characters.
	str = strings.ReplaceAll(str, "+", "%20")
	str = strings.ReplaceAll(str, "*", "%2A")
	str = strings.ReplaceAll(str, "%7E", "~")
	return str
}

Node.js

In this example, JavaScript is used. Before you run the sample code, run the following command on the terminal to download the required modules:

 npm install --save-dev @types/node
const crypto = require('crypto');
const {stringify} = require("node:querystring");
const {request} = require("node:https");

class Request {
    constructor(httpMethod, canonicalUri, host, xAcsAction, xAcsVersion) {
        this.httpMethod = httpMethod;
        this.canonicalUri = canonicalUri || '/';
        this.host = host;
        this.xAcsAction = xAcsAction;
        this.xAcsVersion = xAcsVersion;
        this.headers = {};
        this.body = null;
        this.queryParam = {};
        this.initBuilder();
    }

    initBuilder() {
        const date = new Date();
        this.headers = {
            'host': this.host,
            'x-acs-action': this.xAcsAction,
            'x-acs-version': this.xAcsVersion,
            'x-acs-date': date.toISOString().replace(/\..+/, 'Z'),
            'x-acs-signature-nonce': crypto.randomBytes(16).toString('hex')
        }
    }
}

const ALGORITHM = 'ACS3-HMAC-SHA256';
const accessKeyId = process.env.ALIBABA_CLOUD_ACCESS_KEY_ID;
const accessKeySecret = process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET;

if (!accessKeyId || !accessKeySecret) {
    console.error('ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables must be set.');
    process.exit(1);
}

function getAuthorization(signRequest) {
    try {
        // Step 1: Construct a canonicalized request.
        const canonicalQueryString = Object.entries(signRequest.queryParam)
            .sort((a, b) => a[0].localeCompare(b[0]))
            .map(([key, value]) => `${percentCode(key)}=${percentCode(value)}`)
            .join('&');

        // The request body. If the request body is empty, such as in a GET request, use an empty string as the value of the RequestPayload parameter.
        const requestPayload = signRequest.body || '';
        const hashedRequestPayload = sha256Hex(requestPayload);
        signRequest.headers['x-acs-content-sha256'] = hashedRequestPayload;

        // Convert all header names to lowercase letters.
        signRequest.headers = Object.fromEntries(
            Object.entries(signRequest.headers).map(([key, value]) => [key.toLowerCase(), value])
        );

        const sortedKeys = Object.keys(signRequest.headers)
            .filter(key => key.startsWith('x-acs-') || key === 'host' || key === 'content-type')
            .sort();
        // The request headers that are used for signature calculation. Use semicolons (;) to concatenate all the headers by lowercase header name in alphabetical order.
        const signedHeaders = sortedKeys.join(";")
        // Construct request headers. Concatenate multiple canonicalized request headers by lowercase header name in alphabetical order.
        const canonicalHeaders = sortedKeys.reduce((result, key) => {
            const value = signRequest.headers[key];
            // Format the result string as needed.
            return `${result}${key}:${value}\n`;
        }, '');

        const canonicalRequest = `${signRequest.httpMethod}\n${signRequest.canonicalUri}\n${canonicalQueryString}\n${canonicalHeaders}\n${signedHeaders}\n${hashedRequestPayload}`;
        console.log('canonicalRequest=========>\n', canonicalRequest);

        // Step 2: Construct a string-to-sign.
        const hashedCanonicalRequest = sha256Hex(canonicalRequest);
        const stringToSign = ALGORITHM + '\n' + hashedCanonicalRequest;
        console.log('stringToSign=========>', stringToSign);

        // Step 3: Calculate the signature string.
        const signature = hmac256(accessKeySecret, stringToSign);
        console.log('signature=========>', signature);

        // Step 4: Specify the Authorization header.
        const authorization = `${ALGORITHM} Credential=${accessKeyId},SignedHeaders=${signedHeaders},Signature=${signature}`;
        console.log('authorization=========>', authorization);
        signRequest.headers['Authorization'] = authorization;
    } catch (error) {
        console.error('Failed to get authorization');
        console.error(error);
    }
}

async function callApi(signRequest) {
    try {
        let url = `https://${signRequest.host}${signRequest.canonicalUri}`;
        // Specify request parameters.
        if (signRequest.queryParam) {
            let query = new URLSearchParams();
            for (let [key, value] of Object.entries(signRequest.queryParam)) {
                query.append(key, String(value));
            }
            url += '?' + query.toString();
        }
        // Configure request options.
        let options = {
            method: signRequest.httpMethod.toUpperCase(),
            headers: {}
        };
        // Specify HTTP request headers.
        if (signRequest.headers) {
            for (let [key, value] of Object.entries(signRequest.headers)) {
                options.headers[key] = String(value);
            }
        }
        // Process the request body.
        if (signRequest.body && ['POST', 'PUT'].includes(signRequest.httpMethod.toUpperCase())) {
            options.body = signRequest.body;
        }
        try {
            return (await fetch(url, options)).text();
        } catch (error) {
            // Handler errors.
            console.error('Failed to send request:', error);
        }
    } catch (error) {
        if (error instanceof TypeError) {
            // Handler errors.
            console.error('Invalid URI syntax');
        } else {
            // Handler errors.
            console.error('An unexpected error occurred:', error);
        }
    }
}

function percentCode(str) {
    return encodeURIComponent(str)
        .replace(/\+/g, '%20')
        .replace(/\*/g, '%2A')
        .replace(/~/g, '%7E');
}

function hmac256(key, data) {
    const hmac = crypto.createHmac('sha256', Buffer.from(key, 'binary'));
    hmac.update(data, 'utf8');
    return hmac.digest('hex').toLowerCase();
}

function sha256Hex(str) {
    if (str === null || str === undefined) {
        throw new Error('The specified string cannot be null or undefined.');
    }
    const hash = crypto.createHash('sha256');
    const digest = hash.update(str, 'utf8').digest('hex');
    return digest.toLowerCase();
}

// Example 1: Construct a request for an RPC API operation.
const httpMethod = 'GET';
const canonicalUri = '/';
const host = 'ecs.cn-beijing.aliyuncs.com';
const xAcsAction = 'DescribeInstances';
const xAcsVersion = '2014-05-26';
const signRequest = new Request(httpMethod, canonicalUri, host, xAcsAction, xAcsVersion, xAcsVersion);
signRequest.queryParam = {
    RegionId: 'cn-beijing',
    VpcId: 'vpc-2zeo42r27y4opXXXXXXXX',
}

// Example 2: Construct a POST request for an ROA API operation.
// const httpMethod = 'POST';
// const canonicalUri = '/clusters';
// const host = 'cs.cn-beijing.aliyuncs.com';
// const xAcsAction = 'CreateCluster';
// const xAcsVersion = '2015-12-15';
// const signRequest = new Request(httpMethod, canonicalUri, host, xAcsAction, xAcsVersion, xAcsVersion);
// const body = {
//     name: 'testDemo',
//     region_id: 'cn-beijing',
//     cluster_type: 'ExternalKubernetes',
//     vpcid: 'vpc-2zeo42r27y4opXXXXXXXX',
//     service_cidr: '172.16.3.0/20',
//     security_group_id: 'sg-2zeh5ta2iklXXXXXXXX',
//     vswitch_ids: [
//         'vsw-2ze3aagwn397gXXXXXXXX'
//       ],
// }
// signRequest.body = JSON.stringify(body)
// // Specify the Content-Type header as needed. In this example, JSON is used.
// signRequest.headers['content-type'] = 'application/json';

// Example 3: Construct a GET request for an ROA API operation.
// const httpMethod = 'GET';
// const canonicalUri = '/api/v1/clusters';
// const host = 'cs.cn-beijing.aliyuncs.com';
// const xAcsAction = 'DescribeClustersV1';
// const xAcsVersion = '2015-12-15';
// const signRequest = new Request(httpMethod, canonicalUri, host, xAcsAction, xAcsVersion, xAcsVersion);
// signRequest.queryParam = {
//     cluster_id: 'cd4b2c37e17184bc5a81a928eXXXXXXXX',
//     cluster_type: 'Kubernetes',
//     region_id: 'cn-beijing',
//     name: 'testDemo',
//     page_size: '10',
//     page_number: '1',
// }

getAuthorization(signRequest);
callApi(signRequest).then(r => {
    console.log(r);
});

Fixed parameter values

In this example, fixed parameter values are used to help you verify whether the signature method is used properly. You can calculate a signature based on the following fixed parameter values. If the signature that you generate is the same as the signature generated in this example, your signature calculation process is correct.

Parameter

Value

AccessKeyID

Your AccessKey ID

AccessKeySecret

Your AccessKey secret

x-acs-signature-nonce

3156853299f313e23d1673dc12e1703d

x-acs-date

2023-10-26T10:22:32Z

You can perform the following steps to sign a request:

  1. Construct a canonicalized request.

POST
/
ImageId=win2019_1809_x64_dtc_zh-cn_40G_alibase_20230811.vhd&RegionId=cn-shanghai
host:ecs.cn-shanghai.aliyuncs.com
x-acs-action:RunInstances
x-acs-content-sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
x-acs-date:2023-10-26T10:22:32Z
x-acs-signature-nonce:3156853299f313e23d1673dc12e1703d
x-acs-version:2014-05-26

host;x-acs-action;x-acs-content-sha256;x-acs-date;x-acs-signature-nonce;x-acs-version
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
  1. Construct a string-to-sign.

ACS3-HMAC-SHA256
7ea06492da5221eba5297e897ce16e55f964061054b7695beedaac1145b1e259
  1. Calculate the signature string.

06563a9e1b43f5dfe96b81484da74bceab24a1d853912eee15083a6f0f3283c0
  1. Add the signature string to the request.

POST /?ImageId=win2019_1809_x64_dtc_zh-cn_40G_alibase_20230811.vhd&RegionId=cn-shanghai HTTP/1.1
Authorization: ACS3-HMAC-SHA256 Credential=YourAccessKeyId,SignedHeaders=host;x-acs-action;x-acs-content-sha256;x-acs-date;x-acs-signature-nonce;x-acs-version,Signature=06563a9e1b43f5dfe96b81484da74bceab24a1d853912eee15083a6f0f3283c0
x-acs-action: RunInstances
host: ecs.cn-shanghai.aliyuncs.com
x-acs-date: 2023-10-26T09:01:01Z
x-acs-version: 2014-05-26
x-acs-content-sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
x-acs-signature-nonce: d410180a5abf7fe235dd9b74aca91fc0
user-agent: AlibabaCloud (Mac OS X; x86_64) Java/1.8.0_352-b08 tea-util/0.2.6 TeaDSL/1
accept: application/json

Common errors

Error code

Error message

Solution

SignatureDoesNotMatch

Specified signature does not match our calculation.

During the signature calculation process, you may forget to sort parameters or headers by name in alphabetical order or may add extra spaces. You can read this topic to know more about the signature method and use the fixed parameter values provided in this topic to verify whether your signature calculation process is correct.

IncompleteSignature

The request signature does not conform to Aliyun standards.