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.
Overview
You must add the signature to the Resource Management API request in the following format:
https://Endpoint/?SignatureVersion=1.0&SignatureMethod=HMAC-SHA1&Signature=CT9X0VtwR86fNWSnsc6v8YGOjuE%3D&SignatureNonce=3ee8c1b8-83d3-44af-a94f-4e0ad82fd6cf
- SignatureMethod: the encryption method of the signature string. Set the value to HMAC-SHA1.
- SignatureVersion: the version of the signature encryption algorithm. Set the value to 1.0.
- SignatureNonce: a unique, random number used to prevent replay attacks. You must use different numbers for different requests. We recommend that you use universally unique identifiers (UUIDs).
- Signature: the signature string that is generated after the request is symmetrically encrypted by using the AccessKey secret.
Signature = Base64( HMAC-SHA1( AccessKey Secret, UTF-8-Encoding-Of(StringToSign)) )
Step 1: Compose and encode a string-to-sign
- Create a canonicalized query string by arranging the request parameters.
- Arrange the request parameters (including all common and operation-specific parameters except Signature) in alphabetical order. Note When you use the GET method to submit a request, these parameters constitute the parameter field of the request URL. These parameters are placed after the question mark (?) in the request URI and connected by ampersands (&).
- Encode the names and values of the arranged request parameters in the request URL by using the UTF-8 character set. The following table describes the encoding rules.
Character Encoding rule Uppercase letters, lowercase letters, digits, hyphens (-), underscores (_), periods (.), and tildes (~) These characters do not need to be encoded. Other characters These characters must be percent encoded in the %XY
format.XY
represents the ASCII code of the characters in hexadecimal notation. For example, double quotation marks (") are encoded as%22
.Extended UTF-8 characters These characters must be encoded in the %XY%ZA…
format.Spaces Spaces must be encoded as %20
. Do not encode spaces as plus signs (+).This encoding method is different from the Multipurpose Internet Mail Extensions (MIME) encoding algorithmapplication/x-www-form-urlencoded
, such as thejava.net.URLEncoder
class that is provided by the Java standard library. However, you can apply the MIME encoding algorithm and then replace the plus sign (+) in the encoded string with%20
, the asterisk (*) with%2A
, and%7E
with the tilde (~). You can use the followingpercentEncode
method to implement the algorithm:private static final String ENCODING = "UTF-8"; private static String percentEncode(String value) throws UnsupportedEncodingException { return value != null ? URLEncoder.encode(value, ENCODING).replace("+", "%20").replace("*", "%2A").replace("%7E", "~") : null; }
- Connect the encoded parameter names and values by using equal signs (=).
- Sort the connected parameter name and value pairs in the specified order and connect the pairs by using ampersands (&) to obtain the canonicalized query string.
- Arrange the request parameters (including all common and operation-specific parameters except Signature) in alphabetical order.
- Create a string-to-sign from the encoded canonicalized query string in the following way:
StringToSign= HTTPMethod + "&" + percentEncode("/") + "&" + percentEncode(CanonicalizedQueryString)
The following list describes the parameters:
- HTTPMethod: specifies the HTTP method used to submit a request, such as GET.
- percentEncode("/"): specifies the encoded value (%2F) of a forward slash (/). The encoding follows the URL encoding rules.
- percentEncode(CanonicalizedQueryString): specifies the encoded canonicalized query string based on the URL encoding rules.
Step 2: Calculate the signature string
- Calculate the HMAC value of the string-to-sign based on RFC 2104. Note Use the SHA1 algorithm to calculate the HMAC value of the string-to-sign. The combination of your AccessKey secret and an ampersand (&) (ASCII code 38) is used as the key for the HMAC calculation.
- Encode the HMAC value in Base64 to obtain the signature string.
- Add the signature string to the request as the Signature parameter. Note When the obtained signature value is submitted as the final request parameter value, the value must be URL-encoded like other parameters based on rules defined in RFC 3986.
Example 1: Concatenate parameters
The following example shows how to call the DescribeRegions operation to query Alibaba Cloud regions. In this example, AccessKeyID is set to testid
, and AccessKeySecret is set to testsecret
. Perform the following operations to calculate the signature value:
- Create a canonicalized query string.
https://ros.aliyuncs.com/?Timestamp=2019-08-23T12%3A46%3A24Z&Format=XML&AccessKeyId=testid&Action=DescribeRegions&SignatureMethod=HMAC-SHA1&SignatureNonce=3ee8c1b8-83d3-44af-a94f-4e0ad82fd6cf&Version=2019-09-10&SignatureVersion=1.0
- Create a string-to-sign.
GET&%2F&AccessKeyId%3Dtestid%26Action%3DDescribeRegions%26Format%3DXML%26SignatureMethod%3DHMAC-SHA1%26SignatureNonce%3D3ee8c1b8-83d3-44af-a94f-4e0ad82fd6cf%26SignatureVersion%3D1.0%26Timestamp%3D2019-08-23T12%253A46%253A24Z%26Version%3D2019-09-10
- Calculate the signature value.
The key value used for calculation is
testsecret&
because AccessKeySecret is set totestsecret
. The calculated signature isOLeaidS1JvxuMvnyHOwuJ+uX5qY=
. The Java Base64 encoding method is used in this example.Signature = Base64( HMAC-SHA1( AccessSecret, UTF-8-Encoding-Of(StringToSign) ) )
- Add the
Signature=OLeaidS1JvxuMvnyHOwuJ%2BuX5qY%3D
string that is encoded based on RFC 3986 to the URL in Step 1.https://ros.aliyuncs.com/?SignatureVersion=1.0&Action=DescribeRegions&Format=XML&SignatureNonce=3ee8c1b8-83d3-44af-a94f-4e0ad82fd6cf&Version=2019-09-10&AccessKeyId=testid&Signature=OLeaidS1JvxuMvnyHOwuJ%2BuX5qY%3D&SignatureMethod=HMAC-SHA1&Timestamp=2019-08-23T12%253A46%253A24Z
- Use browsers or tools such as cURL and Wget to send an HTTPS request. The HTTPS request calls the
DescribeRegions
operation to query Alibaba Cloud regions.
Example 2: Use programming languages
The following example shows how to call the DescribeRegions operation to query Alibaba Cloud regions. In this example, AccessKeyID is set to testid
, AccessKeySecret is set to testsecret
, and all request parameters are included in a Java Map<String, String>
object.
- Predefine the encoding method.
private static final String ENCODING = "UTF-8"; private static String percentEncode(String value) throws UnsupportedEncodingException { return value != null ? URLEncoder.encode(value, ENCODING).replace("+", "%20").replace("*", "%2A").replace("%7E", "~") : null; }
- Predefine the time format for the
Timestamp
parameter. TheTimestamp
value must be specified in the ISO 8601 standard. The time must be in UTC+0.private static final String ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; private static String formatIso8601Date(Date date) { SimpleDateFormat df = new SimpleDateFormat(ISO8601_DATE_FORMAT); df.setTimeZone(new SimpleTimeZone(0, "GMT")); return df.format(date); }
- Create a request string.
final String HTTP_METHOD = "GET"; Map parameters = new HashMap(); // Specify request parameters. parameters.put("Action", "DescribeRegions"); parameters.put("Version", "2019-09-10"); parameters.put("AccessKeyId", "testid"); parameters.put("Timestamp", formatIso8601Date(new Date())); parameters.put("SignatureMethod", "HMAC-SHA1"); parameters.put("SignatureVersion", "1.0"); parameters.put("SignatureNonce", UUID.randomUUID().toString()); parameters.put("Format", "XML"); // Sort the request parameters. String[] sortedKeys = parameters.keySet().toArray(new String[]{}); Arrays.sort(sortedKeys); final String SEPARATOR = "&"; // Create a string-to-sign. StringBuilder stringToSign = new StringBuilder(); stringToSign.append(HTTP_METHOD).append(SEPARATOR); stringToSign.append(percentEncode("/")).append(SEPARATOR); StringBuilder canonicalizedQueryString = new StringBuilder(); for(String key : sortedKeys) { // Encode the key and value. canonicalizedQueryString.append("&") .append(percentEncode(key)).append("=") .append(percentEncode(parameters.get(key))); } // Encode the canonicalized query string. stringToSign.append(percentEncode( canonicalizedQueryString.toString().substring(1)));
- Calculate the signature value.
The key value used for calculation is
testsecret&
because AccessKeySecret is set totestsecret
. The calculated signature isOLeaidS1JvxuMvnyHOwuJ+uX5qY=
.// The following sample code demonstrates how to calculate the signature value. final String ALGORITHM = "HmacSHA1"; final String ENCODING = "UTF-8"; key = "testsecret&"; Mac mac = Mac.getInstance(ALGORITHM); mac.init(new SecretKeySpec(key.getBytes(ENCODING), ALGORITHM)); byte[] signData = mac.doFinal(stringToSign.getBytes(ENCODING)); String signature = new String(Base64.encodeBase64(signData));
- Add the
Signature=OLeaidS1JvxuMvnyHOwuJ%2BuX5qY%3D
string that is encoded based on RFC 3986 to the URL in Step 1.https://ros.aliyuncs.com/?SignatureVersion=1.0&Action=DescribeRegions&Format=XML&SignatureNonce=3ee8c1b8-83d3-44af-a94f-4e0ad82fd6cf&Version=2019-09-10&AccessKeyId=testid&Signature=OLeaidS1JvxuMvnyHOwuJ%2BuX5qY%3D&SignatureMethod=HMAC-SHA1&Timestamp=2019-08-23T12%253A46%253A24Z
- Use browsers or tools such as cURL and Wget to send an HTTPS request. The HTTPS request calls the
DescribeRegions
operation to query Alibaba Cloud regions.