ROA-style request body & signature mechanism
You can set the required API parameters in the common request headers. This approach standardizes the signature mechanism and simplifies it by abstracting the differences between API styles. This topic describes the request structure and signing process for Alibaba Cloud SDK V3. You will learn how to construct standard HTTP requests and use the correct signature algorithm to authenticate them. This process ensures the integrity and security of transmitted data. You can refer to this topic if you want to develop your own request signing for Alibaba Cloud OpenAPI.
Request encoding
Requests and responses are encoded using the UTF-8 character set.
RequestHeader (Common request headers)
A complete Alibaba Cloud OpenAPI request consists of the following parts.
Name | Type | Required | Description | Example |
|---|---|---|---|---|
x-acs-action | String | Yes | The name of the API. | RunInstances |
x-acs-version | String | Yes | The API version. | 2014-05-26 |
Authorization | String | Required for non-anonymous requests | The authorization information used to authenticate the request. The format is `Authorization:SignatureAlgorithm Credential=AccessKeyId,SignedHeaders=SignedHeaders,Signature=YOUR_SIGNATURE`. `SignatureAlgorithm` is the signature algorithm. The value is `ACS3-HMAC-SHA256`. `Credential` is your AccessKey ID. You can view your AccessKey ID in the RAM console. To create an AccessKey pair, see Create an AccessKey. `SignedHeaders` are the names of the headers included in the signature. Note: All common request headers except `Authorization` must be included in the signature if they exist. `Signature` is the request signature. For more information, see Signature mechanism. | 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=YOUR_SIGNATURE |
x-acs-signature-nonce | String | No | A unique random number for the signature. It is used to prevent replay attacks. Use a different random number for each request. | d410180a5abf7fe235dd9b74aca91fc0 |
x-acs-date | String | Yes | The UTC time in the ISO 8601 standard. The format is `yyyy-MM-ddTHH:mm:ssZ`, for example, `2018-01-01T12:00:00Z`. The value must be within 15 minutes of the time the request is sent. | 2023-10-26T09:01:01Z |
host | String | Yes | The endpoint. You can find the service endpoint for different areas where the endpoint is deployed in the documentation for each Alibaba Cloud service. | ecs.cn-shanghai.aliyuncs.com |
x-acs-content-sha256 | String | Yes | The result of hashing the request body and then encoding it in Base16. This is the same as `HashedRequestPayload`. | e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 |
x-acs-security-token | String | Required for STS authentication | The value of `SecurityToken` returned from the `AssumeRole` API call. |
Signature mechanism
To ensure secure API calls, Alibaba Cloud authenticates each API request using a signature. You must include signature information in your request, whether you use the HTTP or HTTPS protocol. This topic guides you through the signing process.
Step 1: Construct a canonical request
To sign and authenticate requests using an AccessKey pair, you must first create a canonical request and then sign it. The client and the Alibaba Cloud service API gateway use the same canonical request format. This ensures that the client and the backend produce the same signature for the same HTTP request, which completes the identity verification.
The following pseudocode shows how to construct a canonical request.
CanonicalRequest =
HTTPRequestMethod + '\n' + // The HTTP request method, in uppercase.
CanonicalURI + '\n' + // The canonical URI.
CanonicalQueryString + '\n' + // The canonical query string.
CanonicalHeaders + '\n' + // The canonical headers.
SignedHeaders + '\n' + // The signed headers.
HashedRequestPayload
-
HTTP request method (HTTPRequestMethod)
The uppercase HTTP method name, such as
GETorPOST. -
Canonical URI (CanonicalURI)
The resource path is the part of a URL between the host and the query string. It includes the
/after the host but does not include the?before the query string. You must use a canonical URI when you make a request. This URI is created by encoding each path segment (the strings separated by/) in UTF-8 based on the rules in RFC3986:-
The characters A-Z, a-z, 0-9, and the characters
-,_,., and~are not encoded. -
Other characters are encoded as the
%character followed by the hexadecimal value of the character's ASCII code. For example, the double quotation mark (") is encoded as%22. -
A space character is encoded as
%20, not as a plus sign (+). An asterisk (*) is replaced with%2A, and%7Eis replaced with a tilde (~).If you use
java.net.URLEncoderfrom the Java standard library, you can obtain the encoded string using theencodemethod and then replacing the plus sign (+) with%20, the asterisk (*) with%2A, and%7Ewith the tilde character (~) in the encoded string.
RPC-style APIs use a forward slash (
/) as the CanonicalURI.For ROA-style APIs, this parameter is the value of
pathin the metadata file, such as /api/v1/clusters. -
-
Canonical query string (CanonicalQueryString)
The constructor is as follows:
- Sort the parameters in the query string in ascending order by parameter name. If parameters have the same name, sort them by value.
- URI-encode the name and value of each parameter using the UTF-8 character set based on the rules in RFC3986. The encoding rules are the same as for the CanonicalURI.
- Use an equal sign (
=) to connect the encoded request parameter name and value. For parameters that have no value, use an empty string. - Concatenate the encoded request parameters with an ampersand (
&) in the order specified in Step 4.
If the query string is empty, use an empty string as the canonical query string.
-
Canonical headers (CanonicalizedHeaders)
This is a non-standard HTTP header. You can add parameters from the request, including those with the
x-acs-prefix,host, andcontent-type, to the canonicalized request header. The method is as follows:- Convert all parameter names that require signing to lowercase.
- Sort all parameters alphabetically by parameter name.
- Trim the leading and trailing spaces from the parameter value. For a parameter that has multiple values, trim the leading and trailing spaces from each value, sort the values in ascending order, and then join them with a comma (
,). - Connect the results of Step 2 and Step 3 with a colon (
:) and add a line feed at the end to form a canonical header entry (CanonicalHeaderEntry). - If there are no headers to sign, use an empty string for the list of canonical headers.
All common request headers that meet the requirements, except for
Authorization, must be included in the signature. -
Signed headers list (SignedHeaders)
This list specifies which headers are included in the signature. It corresponds one-to-one with the headers in CanonicalHeaders. You can construct the list as follows:
- Convert the names of the headers included in CanonicalHeaders to lowercase.
- The lowercase names of the request headers are sorted in ascending alphabetical order and separated by semicolons (
;), such ascontent-type;host;x-acs-date. - The pseudocode is as follows:
CanonicalHeaderEntry = Lowercase(HeaderName) + ':' + Trim(HeaderValue) + '\n'
CanonicalHeaders =
CanonicalHeaderEntry0 + CanonicalHeaderEntry1 + ... + CanonicalHeaderEntryN
-
HashedRequestPayload
If the request body is empty, RequestPayload is an empty string. Otherwise, RequestPayload is the JSON string of the request body. Then, HashedRequestPayload is generated by applying a hash function to RequestPayload. The transform rule can be expressed in pseudocode as
HashedRequestPayload = HexEncode(Hash(RequestPayload)).Hashrepresents the message digest function. Currently, the SHA256 algorithm is supported. For example, if the signature protocol isACS3-HMAC-SHA256, you can useSHA256as the hash function.HexEncoderepresents the encoding function that returns the digest in lowercase hexadecimal format (Base16 encoding).
Table 1. Mapping between signature protocols, signature algorithms, and digest functions
Signature Algorithm (SignatureAlgorithm)
Digest function (Hash) used for RequestPayload and CanonicalRequest
The actual signature algorithm used to calculate the signature
SignatureMethod
ACS3-HMAC-SHA256
SHA256
HMAC-SHA256
Step 2: Construct the string to sign
Construct the string to sign (stringToSign) based on the following pseudocode:
StringToSign =
SignatureAlgorithm + '\n' +
HashedCanonicalRequest
-
SignatureAlgorithm
The signature protocol.
ACS3-HMAC-SHA256is currently supported. Algorithms based on MD5 or SHA1 are no longer supported. -
HashedCanonicalRequest
The hashed canonical request string. The calculation method is shown in the following pseudocode:
HashedCanonicalRequest = HexEncode(Hash(CanonicalRequest))
- Create a digest of the canonical request from Step 1 using a hash function (Hash). The specific hash function depends on the signature protocol (SignatureAlgorithm), as shown in Table 1. For example, if the signature protocol is
ACS3-HMAC-SHA256, you can useSHA256as the hash function. - Encode the digest result from the previous step in lowercase hexadecimal format.
Step 3: Calculate the signature
Calculate the signature value (Signature) based on the following pseudocode:
Signature = HexEncode(SignatureMethod(Secret, StringToSign))
- StringToSign: The string to sign constructed in Step 2, encoded in UTF-8.
- SignatureMethod: The signature algorithm. The specific algorithm depends on the signature protocol (SignatureAlgorithm), as shown in Table 1.
- Secret: Your signature key, which is binary data.
- HexEncode: The encoding function that returns the digest in lowercase hexadecimal format (Base16 encoding).
Step 4: Add the signature to the request
After you calculate the signature, construct the Authorization request header in the following format: Authorization:<SignatureAlgorithm> Credential=<AccessKeyId>,SignedHeaders=<SignedHeaders>,Signature=<Signature>
API signature example
To run the Java example, you must add the following Maven dependencies to your pom.xml file.
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.60</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.36</version>
<scope>provided</scope>
</dependency>
package org.example.service;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
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.*;
@Slf4j
public class RoaDemo {
/**
* A date formatting tool to format a date-time string into 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 {
// HTTP Method
private final String httpMethod;
// The request path. When the resource path is empty, use a forward slash (/) as the CanonicalURI.
private final String canonicalUri;
// endpoint
private final String host;
// API name
private final String xAcsAction;
// API version
private final String xAcsVersion;
// headers
TreeMap<String, Object> headers = new TreeMap<>();
// The parameters required to call the API, located in the body. A JSON string.
String body;
// The parameters required to call the API, located in the query. The parameters are sorted in ascending order by parameter name.
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();
}
// init 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());
}
}
/**
* Obtain the Access Key ID and Access Key Secret from environment variables here.
*/
private final static String ACCESS_KEY_ID = "YOUR_ACCESS_KEY_ID";
private final static String ACCESS_KEY_SECRET = "YOUR_ACCESS_KEY_SECRET";
/**
* Signature protocol
*/
private static final String ALGORITHM = "ACS3-HMAC-SHA256";
public static void main(String[] args) throws Exception {
String workspaceId = "YOUR_WORKSPACEID";
String appId = "YOUR_APPID";
// ROA-style request
String httpMethod = "POST"; // Request method
String canonicalUri = "/" + percentCode(workspaceId) + "/ccai/app/" + percentCode(appId) + "/completion";
String host = "contactcenterai.cn-shanghai.aliyuncs.com"; // endpoint
String xAcsAction = "RunCompletion"; // API name
String xAcsVersion = "2024-06-03"; // API version number
Request request = new Request(httpMethod, canonicalUri, host, xAcsAction, xAcsVersion);
// The parameters required to call the API. Sort the parameters in ascending order by parameter name. Parameters with the same name should be sorted by value.
request.queryParam.put("RegionId", "cn-shanghai");
request.headers.put("content-type", "application/json; charset=utf-8");
// Request body
setBody(request);
// Signing process
getAuthorization(request);
// Call the API
callApi(request);
}
private static void setBody(Request requestIn) {
Map<String, Object> bodyMap = buildRunCompletionRequestMap();
requestIn.body = JSONObject.toJSONString(bodyMap);
}
private static Map<String, Object> buildRunCompletionRequestMap() {
// Dialogue content
List<Map<String, String>> sentenceDTOList = new ArrayList<>();
Map<String, String> sentenceDTO1 = new HashMap<>();
sentenceDTO1.put("ChatId", "chat_1");
sentenceDTO1.put("Role", "user");
sentenceDTO1.put("Text", "I want to apply for a credit card");
Map<String, String> sentenceDTO2 = new HashMap<>();
sentenceDTO2.put("ChatId", "chat_2");
sentenceDTO2.put("Role", "agent");
sentenceDTO2.put("Text", "Okay, please wait 10 minutes. I will process it for you now. Please provide your personal information first.");
sentenceDTOList.add(sentenceDTO1);
sentenceDTOList.add(sentenceDTO2);
Map<String, Object> dialogue = new HashMap<>();
dialogue.put("SessionId", "session_01_asdfasdfasd");
dialogue.put("Sentences", sentenceDTOList);
// Fields for information extraction (can be left blank for non-extraction scenarios)
List<Map<String, String>> fieldList = new ArrayList<>();
Map<String, String> field1 = new HashMap<>();
field1.put("Name", "Name");
field1.put("Desc", "User's name");
Map<String, String> field2 = new HashMap<>();
field2.put("Name", "Credit card number");
field2.put("Desc", "User's credit card number");
fieldList.add(field1);
fieldList.add(field2);
// For templateIds, you need to fill in the real template ID. 47L is an example ID.
Map<String, Object> body = new java.util.HashMap<>();
body.put("Dialogue", dialogue);
//body.put("Dimensions", new java.util.ArrayList<>());
body.put("Fields", fieldList);
body.put("ModelCode", "tyxmTurbo");
body.put("Stream", false);
body.put("TemplateIds", Arrays.asList(47L));
return body;
}
private static void callApi(Request request) throws Exception {
try {
// Send the request via HttpClient
String url = "https://" + request.host + request.canonicalUri;
URIBuilder uriBuilder = new URIBuilder(url);
// Add request parameters
for (Map.Entry<String, Object> entry : request.queryParam.entrySet()) {
uriBuilder.addParameter(entry.getKey(), String.valueOf(entry.getValue()));
}
HttpRequestBase 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, StandardCharsets.UTF_8);
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.httpMethod);
throw new IllegalArgumentException("Unsupported HTTP method");
}
// Add HTTP request headers
for (Map.Entry<String, Object> entry : request.headers.entrySet()) {
httpRequest.addHeader(entry.getKey(), String.valueOf(entry.getValue()));
}
System.out.println("curl "+toCurlCommand(httpRequest));
// 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) {
// Exception handling
System.out.println("Failed to send request");
e.printStackTrace();
}
} catch (URISyntaxException e) {
// Exception handling
System.out.println("Invalid URI syntax");
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// Exception handling
System.out.println("UnsupportedEncodingException");
e.printStackTrace();
}
}
public static String toCurlCommand(HttpRequestBase request) throws Exception{
StringBuilder curlCommand = new StringBuilder("curl -X ");
curlCommand.append(request.getMethod()); // GET, POST, etc.
// Add headers
for (org.apache.http.Header header : request.getAllHeaders()) {
curlCommand.append(" -H '");
curlCommand.append(header.getName());
curlCommand.append(": ");
curlCommand.append(header.getValue());
curlCommand.append("'");
}
// Add body if it's a POST or PUT request
if (request instanceof HttpPost || request instanceof HttpPut) {
// TODO: Handle entity
curlCommand.append(" -d '");
curlCommand.append(EntityUtils.toString(((HttpEntityEnclosingRequestBase) request).getEntity()));
curlCommand.append("'");
}
// Add URL
curlCommand.append(" '");
curlCommand.append(request.getURI().toString());
curlCommand.append("'");
return curlCommand.toString();
}
/**
* This method is used to calculate and generate authorization information based on the incoming HTTP request method, canonical URI, query parameters, etc.
*/
private static void getAuthorization(Request request) {
try {
// Step 1: Concatenate the canonical request string
// Request parameters. When the query string is empty, use an empty string as the canonical query string.
StringBuilder canonicalQueryString = new StringBuilder();
request.queryParam.entrySet().stream().map(entry -> percentCode(entry.getKey()) + "=" + percentCode(String.valueOf(entry.getValue()))).forEachOrdered(queryPart -> {
// If canonicalQueryString is not empty, add "&" before the new query parameter.
if (canonicalQueryString.length() > 0) {
canonicalQueryString.append("&");
}
canonicalQueryString.append(queryPart);
});
// Request body. When the request body is empty, such as in a GET request, RequestPayload is a fixed empty string.
String requestPayload = "";
if (request.body != null) {
requestPayload = request.body;
}
// Calculate the hash of the request body
String hashedRequestPayload = sha256Hex(requestPayload);
request.headers.put("x-acs-content-sha256", hashedRequestPayload);
// Construct the request headers. Multiple canonical headers are concatenated after being sorted in ascending order by header name (lowercase).
StringBuilder canonicalHeaders = new StringBuilder();
// List of signed headers. Multiple header names (lowercase) are sorted alphabetically and separated by semicolons (;).
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("Canonical Request:\n" + canonicalRequest);
// Step 2: Concatenate the string to be signed
String hashedCanonicalRequest = sha256Hex(canonicalRequest); // Calculate the hash of the canonical request
String stringToSign = ALGORITHM + "\n" + hashedCanonicalRequest;
System.out.println("String to Sign:\n" + stringToSign);
// Step 3: Calculate the signature
String signature = DatatypeConverter.printHexBinary(hmac256(ACCESS_KEY_SECRET.getBytes(StandardCharsets.UTF_8), stringToSign)).toLowerCase();
System.out.println("Signature:" + signature);
// Step 4: Concatenate the Authorization
String authorization = ALGORITHM + " " + "Credential=" + ACCESS_KEY_ID + ",SignedHeaders=" + signedHeaders + ",Signature=" + signature;
System.out.println("Authorization:" + authorization);
request.headers.put("Authorization", authorization);
} catch (Exception e) {
// Exception handling
System.out.println("Failed to get authorization");
e.printStackTrace();
}
}
/**
* Generate a Message Authentication Code (MAC) using the HmacSHA256 algorithm.
*
* @param key The secret key used to generate the MAC. It must be kept confidential.
* @param str The message to be authenticated with MAC.
* @return Returns the MAC calculated using the HmacSHA256 algorithm.
* @throws Exception Throws an exception if an error occurs during MAC initialization or calculation.
*/
public static byte[] hmac256(byte[] key, String str) throws Exception {
// Instantiate the HmacSHA256 message authentication code generator
Mac mac = Mac.getInstance("HmacSHA256");
// Create a secret key specification to initialize the MAC generator
SecretKeySpec secretKeySpec = new SecretKeySpec(key, mac.getAlgorithm());
// Initialize the MAC generator
mac.init(secretKeySpec);
// Calculate and return the message authentication code
return mac.doFinal(str.getBytes(StandardCharsets.UTF_8));
}
/**
* Calculate the SHA-256 hash of a string and return it as a hexadecimal string.
*
* @param str The string to be hashed with SHA-256.
* @return The result is a lowercase hexadecimal string.
* @throws Exception Throws an exception if an error occurs while getting the SHA-256 message digest instance.
*/
public static String sha256Hex(String str) throws Exception {
// Get the SHA-256 message digest instance
MessageDigest md = MessageDigest.getInstance("SHA-256");
// Calculate the SHA-256 hash of the string s
byte[] d = md.digest(str.getBytes(StandardCharsets.UTF_8));
// Convert the hash value to a lowercase hexadecimal string and return it
return DatatypeConverter.printHexBinary(d).toLowerCase();
}
/**
* URL-encode the specified string.
* Encode the string using the UTF-8 character set and replace specific characters to comply with URL encoding standards.
*
* @param str The string to be URL-encoded.
* @return The encoded string. The plus sign "+" is replaced with "%20", the asterisk "*" with "%2A", and "%7E" with "~".
*/
public static String percentCode(String str) {
if (str == null) {
throw new IllegalArgumentException("Input 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);
}
}
}
Common errors for signature failures
Code | Message | Solution |
SignatureDoesNotMatch | Specified signature does not match our calculation. | During the signing process, you might have forgotten to sort the parameters in ascending order, or you might have added extra spaces. Read the signature mechanism section carefully. You can also verify your signing process using the provided fixed parameter examples. |
IncompleteSignature | The request signature does not conform to Alibaba Cloud standards. |