Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret...

50
API Gateway Development Guide Issue 07 Date 2018-08-31 HUAWEI TECHNOLOGIES CO., LTD.

Transcript of Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret...

Page 1: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

API Gateway

Development Guide

Issue 07

Date 2018-08-31

HUAWEI TECHNOLOGIES CO., LTD.

Page 2: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Copyright © Huawei Technologies Co., Ltd. 2018. All rights reserved.No part of this document may be reproduced or transmitted in any form or by any means without prior writtenconsent of Huawei Technologies Co., Ltd. Trademarks and Permissions

and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.All other trademarks and trade names mentioned in this document are the property of their respectiveholders. NoticeThe purchased products, services and features are stipulated by the contract made between Huawei and thecustomer. All or part of the products, services and features described in this document may not be within thepurchase scope or the usage scope. Unless otherwise specified in the contract, all statements, information,and recommendations in this document are provided "AS IS" without warranties, guarantees orrepresentations of any kind, either express or implied.

The information in this document is subject to change without notice. Every effort has been made in thepreparation of this document to ensure accuracy of the contents, but all statements, information, andrecommendations in this document do not constitute a warranty of any kind, express or implied.

Huawei Technologies Co., Ltd.Address: Huawei Industrial Base

Bantian, LonggangShenzhen 518129People's Republic of China

Website: http://www.huawei.com

Email: [email protected]

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. i

Page 3: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Contents

1 Overview......................................................................................................................................... 1

2 Authentication Modes.................................................................................................................. 2

3 App Authentication.......................................................................................................................33.1 Preparation......................................................................................................................................................................33.2 Setting up a Development Environment.........................................................................................................................43.2.1 Java.............................................................................................................................................................................. 43.2.2 Go.............................................................................................................................................................................. 123.2.3 Python........................................................................................................................................................................153.2.4 C#...............................................................................................................................................................................173.2.5 JavaScript...................................................................................................................................................................183.2.6 PHP............................................................................................................................................................................223.2.7 C++............................................................................................................................................................................ 253.2.8 C.................................................................................................................................................................................253.3 Calling APIs................................................................................................................................................................. 263.3.1 Java............................................................................................................................................................................ 263.3.2 Go.............................................................................................................................................................................. 293.3.3 Python........................................................................................................................................................................303.3.4 C#...............................................................................................................................................................................303.3.5 JavaScript...................................................................................................................................................................313.3.6 PHP............................................................................................................................................................................333.3.7 C++............................................................................................................................................................................ 333.3.8 C.................................................................................................................................................................................353.3.9 curl............................................................................................................................................................................. 373.3.10 Other Programming Languages...............................................................................................................................39

4 IAM Authentication....................................................................................................................414.1 Token Authentication....................................................................................................................................................414.2 AK/SK Authentication................................................................................................................................................. 42

5 None Authentication...................................................................................................................43

6 Backend Signature.......................................................................................................................446.1 Creating a Signature Key..............................................................................................................................................446.2 Signature Algorithm..................................................................................................................................................... 45

API GatewayDevelopment Guide Contents

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. ii

Page 4: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

A Change History........................................................................................................................... 46

API GatewayDevelopment Guide Contents

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. iii

Page 5: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

1 Overview

Chapters 2–5 provide guidance for API users on how to call APIs in the followingauthentication modes:

l None or IAM (token): SDKs are not required for accessing APIs.l App or IAM (AK/SK): SDKs are required for accessing APIs.

Chapter 6 provides guidance for API providers on how to create backend signatures to ensuresecurity access to backend services.

API GatewayDevelopment Guide 1 Overview

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 1

Page 6: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

2 Authentication Modes

The following authentication methods are available for calling APIs:

l App: The AppKey and AppSecret provided by API Gateway are used for signatureauthentication. App authentication allows you to control the sources from which APIcalls are received and to publish APIs on the Marketplace. This authentication mode isrecommended. It is intended for HUAWEI CLOUD tenants.

l IAM: Authentication is performed based on user token or AK/SK. This authenticationmode does not restrict access to APIs, and does not allow APIs to be published on theMarketplace. It is intended for HUAWEI CLOUD tenants.– Token authentication: Requests are authenticated using a token. Token

authentication is recommended for calling open-source APIs.– AK/SK authentication: Requests are signed using an AK and SK in the same way as

in App authentication mode.l None: No authentication is required on requests. This authentication mode does not

restrict access to APIs, and does not allow APIs to be published on the Marketplace. It isintended for all public network users.

API GatewayDevelopment Guide 2 Authentication Modes

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 2

Page 7: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

3 App Authentication

3.1 Preparation3.2 Setting up a Development Environment3.3 Calling APIs

3.1 PreparationBefore accessing an API through an SDK in App authentication mode, you must collect therequired information.

l Obtain the domain name, request URL, and request method of the API.View the API details on the Configuration tab page.

l Publish the API in an environment before you can access it.View the environment in which the API is published on the Configuration tab page.

l Provide a valid AppKey and AppSecret to generate an authenticated signature.Create an App on the Apps page and bind it to the API. Then you can use the AppKeyand AppSecert of the App to access the API. View the AppKey and AppSecret on theApp details page.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 3

Page 8: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

NOTE

l AppKey: indicates the access key ID of the App. It is the unique ID associated with a secretaccess key. The AppKey and AppSecret are together used to obtain an encrypted signature fora request.

l AppSecret: indicates the secret access key used together with an AppKey to sign requests. TheAppKey and AppSecret can be together used to identify a request sender to prevent the requestfrom being modified.

l When sending an API request, add the current time to the X-Sdk-Date header, and addthe signature information to the Authorization header. The signature is valid only withina limited period of time.

3.2 Setting up a Development Environment

3.2.1 Java

Preparing the Environmentl Eclipse: Download Eclipse 3.6.0 or a later version from the Eclipse official website.

l JDK: Download Java Development Kit 1.8.111 or a later version from the Oracleofficial website.

Obtaining the SDK

Download the SDK at https://obs.cn-north-1.myhwclouds.com/apig-sdk/ApiGateway-java-sdk.zip.

Decompress the ApiGateway-java-sdk.zip package. The following table shows the directorystructure of the package.

Name Description

libs\commons-codec-1.6.jar SDK package

libs\commons-logging-1.1.3.jar

libs\httpclient-4.3.6.jar

libs\httpcore-4.3.3.jar

libs\java-sdk-core-3.0.2.jar

libs\joda-time-2.7.jar

src\com\apig\sdk\demo\Main.java Sample code

src\com\apig\sdk\demo\LargeFileUploadDe-mo.java

.classpath Java project configuration file

.project

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 4

Page 9: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

NOTE

Versions of the .jar files may differ from those in the table.

Importing a Project

Step 1 Start Eclipse and choose File > Import.

The Import dialog box is displayed.

Step 2 Choose General > Existing Projects into Workspace and click Next.

The Import Projects dialog box is displayed.

Step 3 Click Browse and select the directory where the SDK is decompressed.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 5

Page 10: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Step 4 Click Finish.

The following figure shows the directory structure of the project.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 6

Page 11: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Main.java is sample code. Modify the parameters to suit your requirements before use. Fordetails about the sample code, see 3.3.1 Java.

----End

Creating a Project

Step 1 Start Eclipse and create a Java project. Specify a project name, for example, java-sdk-demo.Retain the default values for other parameters and click Finish.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 7

Page 12: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Step 2 Import the .jar files in the API Gateway Java SDK.

1. Right-click the created project java-sdk-demo and choose Build Path > Add ExternalArchives.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 8

Page 13: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

2. Select all .jar files in the java\libs directory.

3. Click Open.

Step 3 Create a Package and Main file.

1. Right-click src and choose New > Package.

2. Enter com.apig.sdk.demo for Name.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 9

Page 14: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

3. Click Finish.The Package is created.

4. Right-click com.apig.sdk.demo and choose New > Class.

5. Enter Main for Name and select public static void main(String[] args).

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 10

Page 15: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

6. Click Finish.The Main file is created.

Step 4 View the directory structure of the project.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 11

Page 16: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Before using Main.java, enter the required code according to 3.3.1 Java.

----End

3.2.2 Go

Preparing the Environmentl Download IntelliJ IDEA from the IntelliJ IDEA official website and install it.l Download the Go installation package from the Go official website and install it.l Install the Go plugin on IDEA.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 12

Page 17: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Obtaining the SDKDownload the SDK at https://obs.cn-north-1.myhwclouds.com/apig-sdk/ApiGateway-go-sdk.zip.

Decompress the ApiGateway-go-sdk.zip package, and use the SDK code and sample codefor environment building and API calling.

Name Description

core\escape.go SDK code

core\signer.go

demo.go Sample code

Creating a Project

Step 1 Start IDEA and choose File > New > Project.

On the displayed New Project page, choose Go and click Next.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 13

Page 18: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Step 2 Click ..., select the directory where the SDK is decompressed, and click Finish.

Step 3 View the directory structure shown in the following figure.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 14

Page 19: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

----End

3.2.3 Python

Preparing the Environmentl Download IntelliJ IDEA from the IntelliJ IDEA official website and install it.l Download the Python installation package (version 2.7 or 3.x) from the Python official

website and install it.l Install the Python plugin on IDEA.

Obtaining the SDK

Download the SDK at https://obs.cn-north-1.myhwclouds.com/apig-sdk/ApiGateway-python-sdk.zip.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 15

Page 20: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Decompress the ApiGateway-python-sdk.zip package. The following table shows thedirectory structure of the package.

Name Description

apig_sdk\__init__.py SDK code

apig_sdk\signer.py

main.py Sample code

licenses\license-requests Third-party library license file

Creating a Project

Step 1 Start IDEA and choose File > New > Project.

On the displayed New Project page, choose Python and click Next.

Step 2 Click Next. Click ..., select the directory where the SDK is decompressed, and click Finish.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 16

Page 21: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Step 3 View the directory structure shown in the following figure.

----End

3.2.4 C#

Preparing the Environment

Download Visual Studio from the Visual Studio official website and install it.

Obtaining the SDK

Download the SDK at https://obs.cn-north-1.myhwclouds.com/apig-sdk/ApiGateway-csharp-sdk.zip.

Decompress the ApiGateway-csharp-sdk.zip package. The following table shows thedirectory structure of the package.

Name Description

Signer.cs SDK code

HttpEncoder.cs

Program.cs Sample code

csharp.sln Project files

csharp.csproj

licenses\license-referencesource Third-party library license file

Opening a Project

Double-click csharp.sln in the SDK package to open the project.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 17

Page 22: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

3.2.5 JavaScriptThe JavaScript SDK can run in a Node.js or browser environment. The following describeshow to set up a Node.js development environment.

Preparing the Environmentl Download IntelliJ IDEA from the IntelliJ IDEA official website and install it.

l Download the Node.js installation package from the Node.js official website and installit.

l Install the Node.js plugin on IDEA.

Obtaining the SDK

Download the SDK at https://obs.cn-north-1.myhwclouds.com/apig-sdk/ApiGateway-javascript-sdk.zip.

Decompress the ApiGateway-javascript-sdk.zip package to the current folder. Thefollowing table shows the directory structure of the package.

Name Description

signer.js SDK code

node_demo.js Node.js sample code

demo.html Browser sample code

demo_require.html Browser sample code (loaded usingrequire)

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 18

Page 23: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Name Description

test.js Test case

js\hmac-sha256.js Dependencies

js\moment.min.js

js\moment-timezone-with-data.min.js

licenses\license-crypto-js Third-party library license files

licenses\license-moment

licenses\license-moment-timezone

licenses\license-node

Creating a Project

Step 1 Start IDEA and choose File > New > Project.

In the New Project dialog box, choose Static Web and click Next.

Step 2 Click ..., select the directory where the SDK is decompressed, and click Finish.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 19

Page 24: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Step 3 View the directory structure shown in the following figure.

Step 4 Click Edit Configurations.

Step 5 Click + and select Node.js.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 20

Page 25: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Step 6 Set JavaScript file to node_demo.js and click OK.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 21

Page 26: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

----End

3.2.6 PHP

Preparing the Environmentl Download IntelliJ IDEA from the IntelliJ IDEA official website and install it.l Download the PHP installation package from the PHP official website and install it.l Copy the php.ini-production file from the PHP installation directory to the C:\windows

\ directory, rename the file as php.ini, and then add the following lines to the file:extension_dir = "[PHP installation directory]/ext"extension=opensslextension=curl

l Install the PHP plugin on IDEA.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 22

Page 27: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Obtaining the SDKDownload the SDK at https://obs.cn-north-1.myhwclouds.com/apig-sdk/ApiGateway-php-sdk.zip.

Decompress the ApiGateway-php-sdk.zip package to the current directory. The followingtable shows the directory structure of the package.

Name Description

signer.php SDK code

index.php Sample code

Creating a Project

Step 1 Start IDEA and choose File > New > Project.

On the displayed New Project page, choose PHP and click Next.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 23

Page 28: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Step 2 Click ..., select the directory where the SDK is decompressed, and click Finish.

Step 3 View the directory structure shown in the following figure.

----End

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 24

Page 29: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

3.2.7 C++

Preparing the Environment1. Install the OpenSSL library.

apt-get install libssl-dev

2. Install the curl library.apt-get install libcurl4-openssl-dev

Obtaining the SDK

Download the SDK at https://obs.cn-north-1.myhwclouds.com/apig-sdk/ApiGateway-cpp-sdk.zip.

Decompress the ApiGateway-cpp-sdk.zip package to the current folder. The following tableshows the directory structure of the package.

Name Description

hasher.cpp SDK code

hasher.h

header.h

RequestParams.cpp

RequestParams.h

signer.cpp

signer.h

Makefile Makefile file

main.cpp Sample code

3.2.8 C

Preparing the Environment1. Install the OpenSSL library.

apt-get install libssl-dev

2. Install the curl library.apt-get install libcurl4-openssl-dev

Obtaining the SDK

Download the SDK at https://obs.cn-north-1.myhwclouds.com/apig-sdk/ApiGateway-c-sdk.zip.

Decompress the ApiGateway-c-sdk.zip package to the current folder. The following tableshows the directory structure of the package.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 25

Page 30: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Name Description

signer_common.c SDK code

signer_common.h

signer.c

signer.h

Makefile Makefile file

main.c Sample code

3.3 Calling APIs

3.3.1 JavaNOTE

l This section demonstrates how to access a published API.

l Before accessing an API, you must create and publish the API on the API Gateway console. You canspecify the Mock backend for the API. For details about how to create and publish an API, see theAPI Gateway User Guide.

l The backend of this API is a stub HTTP service, which returns response code 200 and message bodyhello apig.

Step 1 Add the following references to Main.java:import java.io.IOException;import javax.net.ssl.SSLContext;

import org.apache.http.Header;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.methods.HttpRequestBase;import org.apache.http.conn.ssl.AllowAllHostnameVerifier;import org.apache.http.conn.ssl.SSLConnectionSocketFactory;import org.apache.http.conn.ssl.SSLContexts;import org.apache.http.conn.ssl.TrustSelfSignedStrategy;import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils;

import com.cloud.apigateway.sdk.utils.Client; import com.cloud.apigateway.sdk.utils.Request;

Step 2 Construct a request by configuring the following parameters:l AppKey: Specify an AppKey obtained by referring to 3.1 Preparation. The sample

code uses 4f5f626b-073f-402f-a1e0-e52171c6100c.l AppSecrect: Specify an AppSecret obtained by referring to 3.1 Preparation. The

sample code uses e3a59c0f-d2a7-4363-8fbf-af653690d123.l Method: Specify a request method. The sample code uses POST.l url: Request URL of the API, excluding the QueryString and fragment parts. Use your

own domain name bound to the group to which the API belongs or the domain nameissued by the Marketplace when publishing the API on the Marketplace. The sample

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 26

Page 31: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

code uses http://c967a237-cd6c-470e-906f-a8655461897e.apigw.cn-north-1.huaweicloud.com/java-sdk.

l queryString: Specify query parameters to be carried in the URL. Characters (0-9a-zA-Z./;[]\-=~#%^&_+:") are allowed. The sample code uses name=value.

l header: Specify request headers. The sample code uses Content-Type:text/plain. If youare going to publish the API in a non-RELEASE environment, specify an environmentname. The sample code uses x-stage:publish_env_name.

l body: Specify the request body. The sample code uses demo.

The sample code is as follows:

Request request = new Request(); try { request.setAppKey("4f5f626b-073f-402f-a1e0-e52171c6100c"); //Obtain the value when creating an App. request.setAppSecrect("e3a59c0f-d2a7-4363-8fbf-af653690d123"); //Obtain the value when creating an App. request.setMethod("POST"); request.setUrl("http://c967a237-cd6c-470e-906f-a8655461897e.apigw.cn-north-1.huaweicloud.com/java-sdk"); //Obtain the URL when creating an API group. request.addQueryStringParam("name", "value"); request.addHeader("Content-Type", "text/plain"); //request.addHeader("x-stage", "publish_env_name"); //Specify an environment name before publishing the API in a non-RELEASE environment. request.setBody("demo"); } catch (Exception e) { e.printStackTrace(); return; }

Step 3 Sign the request, access the API, and print the result.

The sample code is as follows: CloseableHttpClient client = null; try { HttpRequestBase signedRequest = Client.sign(request);

SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS().build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier()); client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build(); HttpResponse response = client.execute(signedRequest); System.out.println(response.getStatusLine().toString()); Header[] resHeaders = response.getAllHeaders(); for (Header h : resHeaders) { System.out.println(h.getName() + ":" + h.getValue()); } HttpEntity resEntity = response.getEntity(); if (resEntity != null) { System.out.println(System.getProperty("line.separator") + EntityUtils.toString(resEntity, "UTF-8")); }

} catch (Exception e) { e.printStackTrace(); } finally {

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 27

Page 32: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

try { if (client != null) { client.close(); } } catch (IOException e) { e.printStackTrace(); } }

Step 4 Right-click Main.java and choose Run As > Java Application.

Run the project test code.

Step 5 On the Console tab page, view the running result.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 28

Page 33: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

----End

3.3.2 GoStep 1 Import the Go SDK (signer.go) to the project.

import "apig-sdk/go/core"

Step 2 Generate a new Signer and specify an AppKey and AppSecret.s: =core.Signer{ AppKey: "A071fe245-9cf6-4d75-822d-c29945a1e06a, AppSecret: "Ac6e52419-2270-4cb8-8bd4-ae7fdd01dcd5,}

Step 3 Generate a new request, and specify the domain name, method, request URL, and body.r, _ := http.NewRequest("POST", "http://30030113-3657-4fb6-a7ef-90764239b038.apigw.cn-north-1.huaweicloud.com", ioutil.NopCloser(bytes.NewBuffer([]byte("foo=bar"))))

Step 4 Add percent-encoded query parameters to the request.var query[] stringfor key,value := range(map[string]string{ "name": "characters ~!@#$%^&*()_+=", "value": `{ "a": 1, "b": "string" }`, }){ query=append(query, url.QueryEscape(key)+"="+url.QueryEscape(value))}r.URL.RawQuery=strings.Join(query,"&")

Step 5 Add the x-stage header to the request to specify an environment name. Add other headers tobe signed as necessary.r.Header.Add("x-stage", "pro")

Step 6 Execute the following function to add the X-Sdk-Date and Authorization headers for signing:s.Sign(r)

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 29

Page 34: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Step 7 Access the API and check the access result.resp, err := http.DefaultClient.Do(r)body, err := ioutil.ReadAll(resp.Body)

----End

3.3.3 PythonStep 1 Run the pip command to install the requests library.

pip install requests

Step 2 Import apig_sdk to the project.from apig_sdk import signerimport requests

Step 3 Generate a new Signer and specify an AppKey and AppSecret.sig = signer.Signer()sig.AppKey = "071fe245-9cf6-4d75-822d-c29945a1e06a"sig.AppSecret = "c6e52419-2270-4cb8-8bd4-ae7fdd01dcd5"

Step 4 Generate a new request, and specify the domain name, method, request URL, and body.r = signer.HttpRequest()r.scheme = "http"r.host = "30030113-3657-4fb6-a7ef-90764239b038.apigw.cn-north-1.huaweicloud.com"r.method = "POST"r.uri = "/app1"r.body = "{\"a\":1}"

Step 5 Add the query parameters to a dictionary. For example, if the query string is ?a=1&b=2, thecode is as follows:r.query = {"a": "1","b":"2"}

Step 6 Add the x-stage header to the request to specify an environment name. Add other headers tobe signed as necessary.r.headers = {"x-stage": "pro"}

Step 7 Execute the following function to add the X-Sdk-Date and Authorization headers for signing:sig.Sign(r)

Step 8 Access the API and check the access result.resp = requests.request(r.method, r.scheme + "://" + r.host + r.uri, headers=r.headers, data=r.body)print(resp.status_code, resp.reason)print(resp.content)

----End

3.3.4 C#Step 1 Import the C# SDK (Signer.cs) to the project.

using HUAWEI_APIG_SDK;

Step 2 Generate a new Signer and specify an AppKey and AppSecret.Signer signer = new Signer();signer.AppKey = "071fe245-9cf6-4d75-822d-c29945a1e06a";signer.AppSecret = "c6e52419-2270-4cb8-8bd4-ae7fdd01dcd5";

Step 3 Generate a new request, and specify the domain name, method, request URL, and body.HttpRequest r = new HttpRequest();r.method="POST";r.host = "30030113-3657-4fb6-a7ef-90764239b038.apigw.cn-north-1.huaweicloud.com";

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 30

Page 35: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

r.uri = "/app1";r.body = "{\"a\":1}";

Step 4 Add the query parameter of the request to a dictionary. For example, if the query string is ?a=1&b=2, the code is as follows:r.query.Add("a", "1");r.query.Add("b", "2");

Step 5 Add the x-stage header to the request to specify an environment name. Add other headers tobe signed as necessary.r.headers.Add("x-stage", "pro");

Step 6 Execute the following function to generate HttpWebRequest, and add the X-Sdk-Date andAuthorization headers for signing:HttpWebRequest req = signer.Sign(r);

Step 7 Access the API and check the access result.var writer = new StreamWriter(req.GetRequestStream());writer.Write(r.body);writer.Flush();HttpWebResponse resp = (HttpWebResponse)req.GetResponse();var reader = newStreamReader(resp.GetResponseStream());Console.WriteLine(reader.ReadToEnd());

----End

3.3.5 JavaScriptThe JavaScript SDK can run in a Node.js or browser environment.

Node.js

Step 1 Run the npm command to install the moment and moment-timezone modules.npm install moment --savenpm install moment-timezone --save

Step 2 Import signer.js to the project.var signer = require('./signer')var http = require('http')

Step 3 Generate a new Signer and specify an AppKey and AppSecret.var sig = new signer.Signer()sig.AppKey = "071fe245-9cf6-4d75-822d-c29945a1e06a"sig.AppSecret = "c6e52419-2270-4cb8-8bd4-ae7fdd01dcd5"

Step 4 Generate a new request, and specify the domain name, method, request URL, and body.var r = new signer.HttpRequest()r.host = "30030113-3657-4fb6-a7ef-90764239b038.apigw.cn-north-1.huaweicloud.com"r.method = "POST"r.uri = "/app1"r.body = '{"a":1}'

Step 5 Add query parameters of the request to an object. For example, if the query string is ?a=1&b=2, the code is as follows:r.query = { "a":"1","b":"2" }

Step 6 Add the x-stage header to the request to specify an environment name. Add other headers tobe signed as necessary.r.headers = { "x-stage":"pro" }

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 31

Page 36: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Step 7 Execute the following function to generate a request parameter, and add the X-Sdk-Date andAuthorization headers for signing:var opt = sig.Sign(r)

Step 8 Access the API and check the access result. If you access the API using HTTPS, changehttp.request to https.request.var req=http.request(opt, function(res){ console.log(res.statusCode) res.on("data", function(chunk){ console.log(chunk.toString()) })})req.on("error",function(err){ console.log(err.message)})req.write(r.body)req.end()

----End

Browser

To access an API using a browser, create an API with the OPTIONS method, and ensure thatthe response header contains Access-Control-Allow-* fields. For details, see Creating anAPI with the OPTIONS Method. Enable CORS to add the header fields.

Step 1 Import signer.js and dependencies to the HTML page.<script src="js/hmac-sha256.js"></script><script src="js/moment.min.js"></script><script src="js/moment-timezone-with-data.min.js"></script><script src='signer.js'></script>

Step 2 Sign the request and access the API.var sig = new signer.Signer()sig.AppKey = "071fe245-9cf6-4d75-822d-c29945a1e06a"sig.AppSecret = "c6e52419-2270-4cb8-8bd4-ae7fdd01dcd5"var r= new signer.HttpRequest()r.host = "30030113-3657-4fb6-a7ef-90764239b038.apigw.cn-north-1.huaweicloud.com"r.method = "POST"r.uri = "/app1"r.body = '{"a":1}'r.query = { "a":"1","b":"2" }r.headers = { "Content-Type":"application/json" }var opt = sig.Sign(r)var scheme = "https"$.ajax({ type: opts.method, data: req.body, processData: false, url: scheme + "://" + opts.hostname + opts.path, headers: opts.headers, success: function (data) { $('#status').html('200') $('#recv').html(data) }, error: function (resp) { if (resp.readyState === 4) { $('#status').html(resp.status) $('#recv').html(resp.responseText) } else { $('#status').html(resp.state()) } },

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 32

Page 37: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

timeout: 1000});

----End

3.3.6 PHPStep 1 Import the PHP SDK to the code.

require 'signer.php';

Step 2 Generate a new Signer and specify an AppKey and AppSecret.$signer = new Signer();$signer->AppKey = '071fe245-9cf6-4d75-822d-c29945a1e06a';$signer->AppSecret = "c6e52419-2270-4cb8-8bd4-ae7fdd01dcd5";

Step 3 Generate a new request, and specify the domain name, method, request URL, and body.$req = new Request();$req->method = 'GET';$req->scheme = 'https';$req->host = '30030113-3657-4fb6-a7ef-90764239b038.apigw.cn-north-1.huaweicloud.com';$req->uri = '/app1';

Step 4 Add query parameters of the request to an array. For example, if the query string is ?a=1&b=2, the code is as follows:$req->query = array( 'a' => '1', 'b' => '2',);

Step 5 Add the x-stage header to the request to specify an environment name. Add other headers tobe signed as necessary.$req->headers = array( 'x-stage' => 'RELEASE',);

Step 6 Execute the following function to generate a $curl context variable.$curl = $signer->Sign($req);

Step 7 Access the API and check the access result.$response = curl_exec($curl);echo curl_getinfo($curl, CURLINFO_HTTP_CODE);echo $response;curl_close($curl);

----End

3.3.7 C++Step 1 Add the following references to main.c:

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <curl/curl.h>#include "signer.h"

Step 2 Generate a new Signer and specify an AppKey and AppSecret.Signer signer("071fe245-9cf6-4d75-822d-c29945a1e06a", "c6e52419-2270-4cb8-8bd4-ae7fdd01dcd5");

Step 3 Generate a new RequestParams request, and specify the method, domain name, request URI,query strings, and request body.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 33

Page 38: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

RequestParams* request = new RequestParams("POST", "30030113-3657-4fb6-a7ef-90764239b038.apigw.cn-north-1.huaweicloud.com", "/app1", "Action=ListUsers&Version=2010-05-08", "demo");

Step 4 Add the x-stage header to the request to specify an environment name. Add other headers tobe signed as necessary.request->addHeader("x-stage", "RELEASE");

Step 5 Execute the following function to add the generated headers to the request variable.signer.createSignature(request);

Step 6 Use the curl library to access the API and view the access result.static size_tWriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp){ size_t realsize = size * nmemb; struct MemoryStruct *mem = (struct MemoryStruct *)userp;

mem->memory = (char*)realloc(mem->memory, mem->size + realsize + 1); if (mem->memory == NULL) { /* out of memory! */ printf("not enough memory (realloc returned NULL)\n"); return 0; }

memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0;

return realsize;}

//send http request using curl libraryint perform_request(RequestParams* request){ CURL *curl; CURLcode res; struct MemoryStruct resp_header; resp_header.memory = (char*)malloc(1); resp_header.size = 0; struct MemoryStruct resp_body; resp_body.memory = (char*)malloc(1); resp_body.size = 0;

curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init();

curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, request->getMethod().c_str()); std::string url = "http://" + request->getHost() + request->getUri() + "?" + request->getQueryParams(); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); struct curl_slist *chunk = NULL; std::set<Header>::iterator it; for (auto header : *request->getHeaders()) { std::string headerEntry = header.getKey() + ": " + header.getValue(); printf("%s\n", headerEntry.c_str()); chunk = curl_slist_append(chunk, headerEntry.c_str()); } printf("-------------\n"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk); curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, request->getPayload().c_str()); curl_easy_setopt(curl, CURLOPT_NOBODY, 0L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(curl, CURLOPT_HEADERDATA, (void *)&resp_header); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&resp_body); //curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); res = curl_easy_perform(curl); if (res != CURLE_OK) {

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 34

Page 39: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } else { long status; curl_easy_getinfo(curl, CURLINFO_HTTP_CODE, &status); printf("status %d\n", status); printf(resp_header.memory); printf(resp_body.memory); } free(resp_header.memory); free(resp_body.memory); curl_easy_cleanup(curl);

curl_global_cleanup();

return 0;}

Step 7 Run the make command to obtain a main executable file, execute the file, and then view theexecution result.

----End

3.3.8 CStep 1 Add the following references to main.c:

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <curl/curl.h>#include "signer.h"

Step 2 Generate a sig_params_t variable, and specify an AppKey and AppSecret.sig_params_t params;sig_params_init(&params);sig_str_t app_key = sig_str("071fe245-9cf6-4d75-822d-c29945a1e06a");sig_str_t app_secret = sig_str("c6e52419-2270-4cb8-8bd4-ae7fdd01dcd5");params.app_key = app_key;params.app_secret = app_secret;

Step 3 Specify the method, domain name, request URI, query strings, and request body.sig_str_t host = sig_str("30030113-3657-4fb6-a7ef-90764239b038.apigw.cn-north-1.huaweicloud.com");sig_str_t method = sig_str("GET");sig_str_t uri = sig_str("/app1");sig_str_t query_str = sig_str("a=1&b=2");sig_str_t payload = sig_str("");params.host = host;params.method = method;params.uri = uri;params.query_str = query_str;params.payload = payload;

Step 4 Add the x-stage header to the request to specify an environment name. Add other headers tobe signed as necessary.sig_headers_add(&params.headers, "x-stage", "RELEASE");

Step 5 Execute the following function to add the generated headers to the request variable.sig_sign(&params);

Step 6 Use the curl library to access the API and view the access result.static size_tWriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp){

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 35

Page 40: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

size_t realsize = size * nmemb; struct MemoryStruct *mem = (struct MemoryStruct *)userp;

mem->memory = (char*)realloc(mem->memory, mem->size + realsize + 1); if (mem->memory == NULL) { /* out of memory! */ printf("not enough memory (realloc returned NULL)\n"); return 0; }

memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0;

return realsize;}

//send http request using curl libraryint perform_request(RequestParams* request){ CURL *curl; CURLcode res; struct MemoryStruct resp_header; resp_header.memory = malloc(1); resp_header.size = 0; struct MemoryStruct resp_body; resp_body.memory = malloc(1); resp_body.size = 0;

curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init();

curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, params.method.data); char url[1024]; sig_snprintf(url, 1024, "http://%V%V?%V", &params.host, &params.uri, &params.query_str); curl_easy_setopt(curl, CURLOPT_URL, url); struct curl_slist *chunk = NULL; for (int i = 0; i < params.headers.len; i++) { char header[1024]; sig_snprintf(header, 1024, "%V: %V", &params.headers.data[i].name, &params.headers.data[i].value); printf("%s\n", header); chunk = curl_slist_append(chunk, header); } printf("-------------\n"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, params.payload.data); curl_easy_setopt(curl, CURLOPT_NOBODY, 0L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(curl, CURLOPT_HEADERDATA, (void *)&resp_header); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&resp_body); //curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); res = curl_easy_perform(curl); if (res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } else { long status; curl_easy_getinfo(curl, CURLINFO_HTTP_CODE, &status); printf("status %d\n", status); printf(resp_header.memory); printf(resp_body.memory); } free(resp_header.memory); free(resp_body.memory); curl_easy_cleanup(curl);

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 36

Page 41: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

curl_global_cleanup();

//free signature params sig_params_free(&params);

sig_str_t trim; sig_str_t str = sig_str(" aaa "); sig_trim_str(&str, &trim); char buf[100]; sig_snprintf(buf, 100, "%V", &trim); printf("'%s'", buf); return 0;}

Step 7 Run the make command to obtain a main executable file, execute the file, and then view theexecution result.

----End

3.3.9 curlStep 1 Use the JavaScript SDK to generate a curl command.

Download the JavaScript SDK and decompress it. Open demo.html in a browser. Thefollowing figure shows the demo page.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 37

Page 42: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Step 2 Specify the AppKey, AppSecret, method, protocol, domain name, and URL. For example:AppKey=071fe245-9cf6-4d75-822d-c29945a1e06aAppSecret=c6e52419-2270-4cb8-8bd4-ae7fdd01dcd5Method=POSTScheme=httpsHost=30030113-3657-4fb6-a7ef-90764239b038.apigw.cn-north-1.huaweicloud.comUrl=/

Step 3 Specify query parameters and headers in JSON format, and set the request body.

Step 4 Click Send request to generate a curl command. Copy the curl command to the CLI toaccess the API.$ curl -X POST "https://30030113-3657-4fb6-a7ef-90764239b038.apigw.cn-north-1.huaweicloud.com/" -H "X-Sdk-Date: 20180530T115847Z" -H "Authorization: SDK-HMAC-SHA256 Access=071fe245-9cf6-4d75-822d-c29945a1e06a, SignedHeaders=host;x-sdk-date, Signature=9e5314bd156d517a0a4fd9018d1fe80f4594e015cd248c9f168dd3e5765fdde4" -d ""Congratulations, sdk demo is running

----End

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 38

Page 43: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

3.3.10 Other Programming Languages

App Authentication Principle

Generating an App Signature by Using Another Programming Language

Step 1 Obtain the following HTTP headers for signature calculation. X-Sdk-Date is mandatory. Hostand other HTTP headers are optional.l Host: obtained from the endpoint in a request.l X-Sdk-Date: generated based on the current system time. The format is

yyyyMMddThhmmssZ, for example, 20150830T123600Z.l Other HTTP headers

Step 2 Calculate the CanonicalRequest string.CanonicalRequest = HTTPRequestMethod + '\n' + CanonicalURI + '\n' + CanonicalQueryString + '\n' + CanonicalHeaders + '\n' + SignedHeaders + '\n' + HexEncode(SHA256(RequestPayload))l CanonicalURI: resource path.l CanonicalQueryString: query parameters in alphabetical order after percent encoding.

The value is a null string if no query parameters are set.l CanonicalHeaders format:

CanonicalHeaders = CanonicalHeadersEntry0 + CanonicalHeadersEntry1 + ... (sorted inalphabetical order)CanonicalHeadersEntry = Lowercase(HeaderName) + ':' + Trimall(HeaderValue) + '\n'

l SignedHeaders format:SignedHeaders = Lowercase(HeaderName0) + ';' + Lowercase(HeaderName1) + ";" + ...The SignedHeaders are sorted by HeaderName in alphabetical order.

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 39

Page 44: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Step 3 Calculate the StringToSign string.StringToSign = 'SDK-HMAC-SHA256' + '\n' + RequestDate + '\n' + HashedCanonicalRequest))l RequestDate: same as the X-Sdk-Date header.l HashedCanonicalRequest: SHA256 hash value of CanonicalRequest.

Step 4 Calculate the signature.signature = HexEncode(HMAC_SHA256(AppSecret, StringToSign))

Step 5 Generate signature information to Request.

Add the signature information to the Authorization header.

Authorization: SDK-HMAC-SHA256 Access=AppKey, SignedHeaders=SignedHeaders, Signature=signature

----End

API GatewayDevelopment Guide 3 App Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 40

Page 45: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

4 IAM Authentication

4.1 Token Authentication

4.2 AK/SK Authentication

4.1 Token Authentication

ScenarioIn token authentication mode, you must obtain the user token, and add X-Auth-Token to therequest header of the service interface when calling an API.

This section describes how to call an API to complete token authentication.

Procedure1. Obtain a token by following the procedure in Obtaining a User Token. Send POST

https://IAM endpoint/v3/auth/tokens to obtain the endpoint of IAM and the regionname in the message body. For details, see Regions and Endpoints. After the request isprocessed, the value of X-Subject-Token in the message header is the token value.An example request is as follows:

NOTE

Replace the texts in italic in the following example with actual values. For details, see the Identityand Access Management API Reference.

{ "auth": { "identity": { "methods": [ "password" ], "password": { "user": { "name": "username", "password": "password", "domain": { "name": "domainname" } } } },

API GatewayDevelopment Guide 4 IAM Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 41

Page 46: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

"scope": { "project": { "name": "cn-north-1" //The region name cn-north-1 is used as an example.

} } }}

2. Make a call to a service API, add X-Auth-Token to the message header, and set the valueof X-Auth-Token to the token obtained in step 1. For example, curl aaaa.com/bbbb –H"X-Auth-Token:$token".

4.2 AK/SK AuthenticationThis section describes how to use AK and SK to sign requests.

NOTE

l AK is a unique identifier that is associated with a secret access key; the access key ID and secretaccess key are used together to sign requests cryptographically.

l SK is a key that is used in conjunction with an access key ID to cryptographically sign requests.Signing a request identifies the sender and prevents the request from being altered.

Generating an AK and SKFor details on how to generate an AK and SK, see Managing Access Keys.

Generating a SignatureGenerate a signature in the same way as in App authentication mode. Replace AppKey withAK and replace AppSecret with SK to complete the signing and request. You can signrequests to access APIs by using Java, Go, Python, C#, JavaScript, PHP, C, or C++.

API GatewayDevelopment Guide 4 IAM Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 42

Page 47: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

5 None Authentication

APIs can be directly accessed without requiring authentication.

API GatewayDevelopment Guide 5 None Authentication

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 43

Page 48: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

6 Backend Signature

6.1 Creating a Signature Key6.2 Signature Algorithm

6.1 Creating a Signature KeyScenario

Backend signature is used for backend services to verify the identity of API Gateway. Thisensures the security of backend services that receive requests from API Gateway. Whenaccessing a backend service, API Gateway uses the configured key pair to sign the requestand sends the signed request to the backend service. The backend service verifies thesignature to ensure secure access while rejecting unsigned requests.

ProcedureStep 1 On the API Gateway console, choose API Publishing > Signature Keys.

Step 2 Click Create Signature Key.

API GatewayDevelopment Guide 6 Backend Signature

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 44

Page 49: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

Step 3 In the Create Signature Key dialog box, set key information and click OK.

Step 4 In the signature key list, click Bind to API in the Operation column to apply the signaturekey in an environment in which APIs are published.

----End

6.2 Signature AlgorithmUse the signature algorithm described in 3.3.1 Java to sign requests. Replace AppKey andAppSecret respectively with Key and Secret of a signature key. Backend services can signrequests in the same way, and verify API validity by checking whether the signature isconsistent with that in the Authorization header sent by API Gateway.

Add X-Proxy-Signed-Headers (SignedHeaders field sent to a backend) to the requestheader to specify headers to be signed by API Gateway, and separate multiple headers withsemicolons.

API GatewayDevelopment Guide 6 Backend Signature

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 45

Page 50: Development Guide - developer-res-cbc-cn.obs.cn-north-1 ...€¦ · l App: The AppKey and AppSecret provided by API Gateway are used for signature authentication. App authentication

A Change History

Table A-1 Change history

Date Description

2018-08-31 Added the C and C++ SDKs.

2018-05-30 Added the PHP SDK.

2018-05-02 Added the Go, Python, C#, and JavaScript SDKs.

2018-04-04 Modified the document outline.

2018-03-09 Added section "AK/SK Signature Design" and chapter"Backend Signature".

2018-01-31 Added section "Uploading Large Files".

2017-12-25 This issue is the first official release.

API GatewayDevelopment Guide A Change History

Issue 07 (2018-08-31) Copyright © Huawei Technologies Co., Ltd. 46