v3 API signature mechanism

Updated at:

This topic describes the v3 API signature mechanism and how to use it.

OpenSearch authenticates every request that it receives. It verifies the identity of the request sender by using symmetric encryption based on an AccessKey ID and an AccessKey secret.

The AccessKey ID and AccessKey secret are issued to visitors by Alibaba Cloud. You can apply for and manage them on the official Alibaba Cloud website. The AccessKey ID identifies the visitor.

The AccessKey secret is the key that is used to encrypt the signature string and to verify the signature string on the server side. It must be kept strictly confidential and must be known only to Alibaba Cloud and the user.

Supported application types

  • Advanced Edition

  • Standard Edition

Communication protocol

Only HTTP is supported.

Request methods

  • Searching data must use: GET

  • Pushing data must use: POST

Calculate the Authorization field

You must add the Authorization header to the HTTP request headers to carry the signature information, which indicates that the request is authorized. The request headers must also include the relevant headers listed under "Request header" in the "Signature example" section of this topic.

All parameters included in the request headers must be used in the signature calculation, such as Content-Md5, Content-Type, Date, and HTTP proprietary headers. Note that in "Authorization: OPENSEARCH ", OPENSEARCH is followed by a space.

"Authorization: OPENSEARCH " + AccessKeyId + ":" + Signature
Signature = base64(hmac-sha1(AccessKeySecret,
            VERB + "\n"
            + Content-Md5 + "\n"
            + Content-Type + "\n"
            + Date + "\n"
            + CanonicalizedOpenSearchHeaders
            + CanonicalizedResource))

Calculate the HMAC signature value from the preceding string to sign as defined in RFC 2104

  • The signature method is HMAC-SHA1 as defined in RFC 2104.

  • The string to sign must be in UTF-8 format.

  • A string to sign that contains Chinese characters must first be UTF-8 encoded before the final signature is calculated with the AccessKeySecret.

  • The order of the signature parameters must be the same as shown above.

Parameter

Description

AccessKeyId

Cannot be empty. The Authorization header of the request uses this AccessKeyId value, which identifies the user who accesses the specified application.

AccessKeySecret

Cannot be empty. The key that is required for the signature.

VERB

Cannot be empty. The request method, that is, the HTTP request method, such as PUT, GET, POST, HEAD, or DELETE. The method varies by API operation.

\n

The line feed character.

Content-MD5

Cannot be empty when the request body has content. The value is the MD5 value of the request body. This header is used to check message validity, that is, whether the message content is the same as when it was sent. Example: 4991ef0788236a8f280fed0db928e74e

For requests that do not send a body, such as query requests, leave this value empty. For more information, see RFC2616 Content-MD5.

Content-Type

application/json

Date

Cannot be empty. The time of the operation. It must be in ISO format accurate to the second, such as 2019-02-25T10:09:57Z, and must be in UTC. If this time differs from the time of the OpenSearch server by more than 10 minutes in either direction, the server rejects the request and returns an HTTP 403 error.

CanonicalizedOpenSearchHeaders

Cannot be empty. Used to distinguish each request. It is the combination of HTTP proprietary headers prefixed with X-Opensearch-, such as X-Opensearch-Nonce. During signing, the names of these HTTP proprietary headers must be all lowercase, such as x-opensearch-nonce. When these HTTP proprietary headers are used as request header parameters, they must keep their original name format. If the request headers do not contain these HTTP proprietary headers, this parameter is not used in the signature calculation and is removed directly from the signature method.

CanonicalizedResource

Cannot be empty. The path of the request, such as /v3/openapi/apps/app_schema_demo/search?fetch_fields=name&query=query%3Dname%3A%27%E6%96%87%E6%A1%A3%27%26%26sort%3Did%26%26config%3Dformat%3Afulljson

Query requests

Request signature parameter

Required

Request header parameter

Required

AccessKeySecret

Yes

Date

Yes

VERB

Yes

X-Opensearch-Nonce

Yes

Date

Yes

Authorization

Yes

x-opensearch-nonce

Yes

canonicalized_resource

Yes

  • The parameter values in the headers must be the same as the corresponding parameter values in the signature method.

  • We recommend that you add all of the following parameters to the request headers: Content-Md5, Content-Type, Date, CanonicalizedOpenSearchHeaders, and Authorization. Including only the required parameters may cause errors and should be avoided.

  • All parameters included in the request headers must be used in the signature calculation.

Push requests

Request signature parameter

Required

Request header parameter

Required

AccessKeySecret

Yes

Content-MD5

Yes

VERB

Yes

Date

Yes

Content-MD5

Yes

Authorization

Yes

Date

Yes

canonicalized_resource

Yes

  • The parameter values in the headers must be the same as the corresponding parameter values in the signature method.

  • We recommend that you add all of the following parameters to the request headers: Content-Md5, Content-Type, Date, CanonicalizedOpenSearchHeaders, and Authorization. Including only the required parameters may cause errors and should be avoided.

  • All parameters included in the request headers must be used in the signature calculation.

Construct CanonicalizedOpenSearchHeaders

All HTTP proprietary headers prefixed with X-Opensearch- are referred to as CanonicalizedOpenSearchHeaders. Other headers that are not HTTP proprietary headers are not included in the verification.

  1. Fill in the values of all HTTP proprietary headers prefixed with X-Opensearch-, such as X-Opensearch-Nonce : 155108**********. The Nonce value can be composed of a 10-digit timestamp followed by a 6-digit random value (100000 to 999999), such as 155108**********. Then, remove all HTTP proprietary headers whose values are empty.

  2. Sort the HTTP proprietary headers that have values in ascending lexicographical order by name.

  3. Convert the sorted proprietary header names to lowercase. For example, convert X-Opensearch-Nonce : 155108********** to x-opensearch-nonce : 155108**********.

  4. Remove any spaces on both sides of the separator between each header and its value. For example, after the spaces are removed, x-opensearch-nonce : 155108********** becomes x-opensearch-nonce:155108**********.

  5. Finally, treat each header and its value as one item, and join the items with \n to form the final CanonicalizedOpenSearchHeaders. Note that the last item must also be followed by \n.

Note
  1. If the query request headers do not contain any HTTP proprietary headers, that is, the CanonicalizedOpenSearchHeaders parameter contains no HTTP proprietary header at all, no \n is needed. Simply remove the CanonicalizedOpenSearchHeaders signature parameter from the signature method. This parameter is then not used in the signature calculation.

  2. When you add HTTP proprietary headers to the request headers, do not use the converted lowercase form. Use the original format.

Construct CanonicalizedResource

  • The string to sign must be in UTF-8 format. A string to sign that contains Chinese characters must first be UTF-8 encoded before the final signature is calculated with the AccessKeySecret.

  • For queries: CanonicalizedResource = path + ? + query

  • For pushes: CanonicalizedResource = path

Construct the path part

URL-encode the path, and then replace %2F with /. Replace app_schema_demo in the following examples with the name of your application. Common paths are as follows:

  • Path for search queries: /v3/openapi/apps/app_schema_demo/search

  • Path for suggest queries: /v3/openapi/suggestions/suggestion_name/actions/search

  • Final request string for querying information about a specified application. Replace "appid" with the ID of the application to query. The request must include the Authorization signature parameter. No query parameters need to be specified. /v3/openapi/apps/appid

  • Path for pushing data. tab is the name of the specific table in the application to which data is pushed. Replace it with the name of your application table. /v3/openapi/apps/app_schema_demo/tab/actions/bulk

Construct the query part

The query part consists of query parameters in the form of key-value pairs.

  1. Set values for the query parameters that you want to specify, and remove parameters whose values are empty. Parameters with empty values are not used in the signature calculation.

  2. Sort the parameters in ascending lexicographical order, first by parameter name and then by parameter value.

  3. URL-encode each parameter name and parameter value in RFC 3986 mode, and then join each parameter name and its value with =.

  4. Join the query parameters with & and store the result in the query string.

  5. Finally, concatenate the parts in the format of path + ? + query to form the CanonicalizedResource string. This completes the construction of the CanonicalizedResource parameter for a query operation. Example: /v3/openapi/apps/app_schema_demo/search?fetch_fields=name&query=query%3Dname%3A%27%E6%96%87%E6%A1%A3%27%26%26sort%3Did%26%26config%3Dformat%3Afulljson

    • The main parameters and parameter values in the preceding request string are as follows:

      • fetch_fields=name

    • The clauses and values in the query parameter of the preceding request string are as follows. The first query is the query parameter, and the second is the query clause, followed by other related clauses. In this example, \u6587\u6863 represents a two-character Chinese search term meaning "document", which is URL-encoded as %E6%96%87%E6%A1%A3 in the request string above. The Unicode escapes are shown for illustration only. Decode them into the actual Chinese characters before you enter the query.

      • query=query=name:'\u6587\u6863'&&sort=id&&config=format:fulljson

Note

Before URL encoding, the query clauses in the query parameter must be joined with &&. For push operations, you only need to add the path part to the CanonicalizedResource string.

Construct the Authorization field

For the construction method, see the description at the beginning of this topic. The field must be added to the request headers. For example, if the AccessKeyId is LTAI**************** and the Signature is 1P7tfE****, the Python 3 sample code is roughly as follows:

headers['Authorization'] = 'OPENSEARCH ' + 'LTAI****************' + ':' + '1P7tfE****'

Signature example

Assume that the parameter values are as follows:

  • Authorization: OPENSEARCH LTAI****************:1P7tfE****

  • AccessKeySecret: yourAccessKeySecret

  • Request method: GET

  • Content-MD5: empty, because this is a query request

  • Content-Type: application/json

  • Date: 2019-02-25T10:09:57Z

  • CanonicalizedOpenSearchHeaders: x-opensearch-nonce:15510****1704

  • CanonicalizedResource: /v3/openapi/apps/app_schema_demo/search?fetch_fields=name&query=query%3Dname%3A%27%E6%96%87%E6%A1%A3%27%26%26sort%3Did%26%26config%3Dformat%3Afulljson

Request header

Signature string formula

Example

‘Content-MD5’: ‘’,

‘Content-Type’: ‘application/json’,

‘Authorization’: ‘OPENSEARCH LTAI****************:1P7tfE****’,‘X-Opensearch-Nonce’: ‘155108**********’,‘Date’: ‘2019-02-25T10:09:57Z’

Signature = base64(hmac-sha1(AccessKeySecret,VERB + “\n”+ Content-Md5 + “\n”+ Content-Type + “\n”+ Date + “\n”+ CanonicalizedOpenSearchHeaders+ CanonicalizedResource))

yourAccessKeySecret,GET\n\napplication/json\n2019-02-25T10:09:57Z\nx-opensearch-nonce:155108**********\n/v3/openapi/apps/app_schema_demo/search?fetch_fields=name&query=query%3Dname%3A%27%E6%96%87%E6%A1%A3%27%26%26sort%3Did%26%26config%3Dformat%3Afulljson

Note

The parameter values in the request headers must be the same as the corresponding parameter values in the signature method.

Calculate the signature by using the following method

  • Use hash_hmac and base64_encode encoding to generate the encrypted value as the Signature.

Python 3 sample code:

import hmac
import base64
signature_string = '\n'.join(['GET',
                              '',
                              'application/json',
                              '2019-02-25T10:09:57Z',
                              'x-opensearch-nonce:1551089397451704',
                              '/v3/openapi/apps/app_schema_demo/search?fetch_fields=name&query=query%3Dname%3A%27%E6%96%87%E6%A1%A3%27%26%26sort%3Did%26%26config%3Dformat%3Afulljson'])
signature_hmac = hmac.new('yourAccessKeySecret'.encode('utf-8'), signature_string.encode('utf-8'), 'sha1')
signature = base64.b64encode(signature_hmac.digest())

If the AccessKeySecret is yourAccessKeySecret, the signature value generated by the preceding method is 1P7tfE****.

Construct the request string

Request string = host + CanonicalizedResource

You must add the Authorization header to the HTTP request headers to carry the signature information, which indicates that the request is authorized. The headers must also include the relevant request headers mentioned above. host is the API endpoint of the application.

  • Final search query request string: http://host/v3/openapi/apps/app_schema_demo/search?fetch_fields=name&query=query%3Dname%3A%27%E6%96%87%E6%A1%A3%27%26%26sort%3Did%26%26config%3Dformat%3Afulljson

  • Final suggest query request string: http://host/v3/openapi/apps/{appName}/suggest/{suggestName}/search?hits=10&query=%E6%A0%87%E9%A2%98

  • Final request string for querying information about a specified application. The last part is the "appid" value. Assume that the value is 120001234. After replacement, the string is as follows. This query request must also include the Authorization signature parameter. No query parameters need to be specified. http://host/v3/openapi/apps/120001234

  • Final request string for pushing data. The data to push must be placed in the request body. http://host/v3/openapi/apps/app_schema_demo/tab/actions/bulk

Note

  • The official v3 Java SDK, PHP SDK, Python SDK, and C# SDK have been released. The PHP SDK, Python SDK, and C# SDK include source code that implements the v3 API signature process, and you can call these methods directly. You can also refer to the signature implementation source code of the PHP SDK, Python SDK, and C# SDK to implement SDKs in other languages.

  • SDKs that users implement based on this topic and the source code are maintained by the users themselves.

Application schema template

{
  "name": "app_schema_demo",
  "type": "standard",
  "schema": {
    "indexes": {
      "search_fields": {
        "id": {
          "fields": [
            "id"
          ]
        },
        "name": {
          "fields": [
            "name"
          ],
          "analyzer": "chn_standard"
        },
        "phone": {
          "fields": [
            "phone"
          ],
          "analyzer": "fuzzy"
        },
        "int_arr": {
          "fields": [
            "int_arr"
          ]
        },
        "literal_arr": {
          "fields": [
            "literal_arr"
          ]
        },
        "cate_id": {
          "fields": [
            "cate_id"
          ]
        }
      },
      "filter_fields": [
        "id",
        "int_arr",
        "literal_arr",
        "float_arr",
        "cate_id"
      ]
    },
    "tables": {
      "tab": {
        "name": "tab",
        "fields": {
          "id": {
            "name": "id",
            "type": "INT",
            "primary_key": true
          },
          "name": {
            "name": "name",
            "type": "TEXT",
            "primary_key": false
          },
          "phone": {
            "name": "phone",
            "type": "SHORT_TEXT",
            "primary_key": false
          },
          "int_arr": {
            "name": "int_arr",
            "type": "INT_ARRAY",
            "primary_key": false
          },
          "literal_arr": {
            "name": "literal_arr",
            "type": "LITERAL_ARRAY",
            "primary_key": false
          },
          "float_arr": {
            "name": "float_arr",
            "type": "FLOAT_ARRAY",
            "primary_key": false
          },
          "cate_id": {
            "name": "cate_id",
            "type": "INT",
            "primary_key": false
          }
        },
        "primary_table": true
      }
    },
    "route_field": null
  },
  "data_sources": [],
  "first_ranks": {},
  "second_ranks": {},
  "summary": [],
  "fetch_fields": [
    "id",
    "name",
    "phone",
    "int_arr",
    "literal_arr",
    "float_arr",
    "cate_id"
  ],
  "quota": {
    "qps": 6,
    "doc_size": 0.3
  }
}