Help Center > > API Reference> Calling APIs> Authentication

Authentication

Updated at: Aug 13, 2019 GMT+08:00

Requests for calling an API can be authenticated using either of the following methods:

  • Token-based authentication: Requests are authenticated using a token.
  • AK/SK-based authentication: Requests are authenticated by encrypting the request body using an AK/SK pair. AK/SK authentication is recommended because it provides higher security than token authentication.

Token-based Authentication

If you use a token for authentication, you must obtain your token and add X-Auth-Token to the headers of API requests.

  1. Send POST https://IAM endpoint/v3/auth/tokens.

    Obtain the endpoint of the IAM and the region name in the message body. You can obtain the information from Regions and Endpoints.

    An example request is as follows:
    NOTE:

    Replace contents in italic in the sample codes with actual contents. For details, see API Reference of the Identity and Access Management (IAM) Service.

    {
      "auth": {
        "identity": {
          "methods": [
            "password"
          ],
          "password": {
            "user": {
              "name": "username",
              "password": "******",
              "domain": {
                "name": "domainname"
              }
            }
          }
        },
        "scope": {
          "project": {
             "name": "ap-southeast-1" //The region name ap-southeast-1 is used an example.
          }
        }
      }
    }

  2. For details about how to obtain a token, see section "Obtaining a User Token" in API Reference of the Identity and Access Management (IAM) Service. After the response is received, the value of X-Subject-Token in the response header is the token value.
  3. You can use either of the following methods to call an API:

    Method 1: Add X-Auth-Token to the request header and set X-Auth-Token to the token obtained in 2.

    Method 2: Add Authorization to the request header. The value of Authorization is Bearer ${token}, and the value of ${token} is the token obtained in 2.

AK/SK Authentication

Use the AK/SK encryption method to verify the identity of a request sender. If you use the AK/SK for authentication, you must obtain the signature through the request signing process and add the signature to the headers of API requests.

NOTE:

AK: indicates the access key ID. It is the unique ID associated with the secret access key. AK is together used with SK to encrypt and sign requests.

SK: indicates the secret access key together used with the access key ID to sign requests. AK and SK can be used together to identify a request sender to prevent the request from being modified.

  1. Obtain an AK/SK file. If an AK/SK file has been obtained, skip this step and find the AK/SK file that has been downloaded. Generally, the file name is credentials.csv.

    1. Sign up and log in to the management console.
    2. Click the username and choose My Credential from the drop-down list.
    1. Click Access Keys.
    2. Click Add Access Key. The Add Access Key page is displayed.
    3. Enter the password used for the current login.
    4. Enter the authentication code received in the email or mobile phone.
      NOTE:

      For users created in IAM, if no email address or mobile phone is specified during the user creation, you need to authenticate only the login password.

    5. Click OK to download the AK/SK file.
      NOTE:

      Keep the AK/SK file confidential to prevent information leakage.

  2. Introduce the API gateway signing SDK in the project.

    1. Download the API gateway signing tool from:

      http://esdk.huawei.com/ilink/esdk/download/HW_456706

    2. Decompress the downloaded package to obtain a .jar file.
    3. Add the decompressed .jar file to the project as a dependency package. The following figure shows an example.
      Figure 1 Decompressing the .jar file

  3. Sign the request.

    The signing method is integrated into the .jar file added in Step 2. Before sending the request, you need to sign the request content. The signature obtained is included in the HTTP header of the request.

    The following describes how to call the POST method to sign the request.

    1. Initialize POST.

      See the code snippet in Demo.java. Values of the AK/SK, request URL, and request body are assigned in POST. Signing is implemented based on the accessService.access() method.

          public static void post(String ak, String sk, String requestUrl, String postbody)
              throws UnsupportedEncodingException {
      
              AccessService accessService = new AccessServiceImpl(serviceName, region, ak, sk);
              URL url = null;
              try {
                  url = new URL(requestUrl);
              } catch (MalformedURLException e) {
                  e.printStackTrace();
              }
              InputStream content = new ByteArrayInputStream(postbody.getBytes("UTF8"));
              HttpMethodName httpMethod = HttpMethodName.POST;
              HttpResponse response;
      
              try {
                  response = accessService.access(url, content, (long) postbody.getBytes("UTF8").length, httpMethod);
                  System.out.println(convertStreamToString(response.getEntity().getContent()));
              } catch (Exception e) {
                  e.printStackTrace();
              } finally {
                  accessService.close();
              }
          }
    2. Create a request for signing. The object is the method in the SDK package: com.cloud.sdk.DefaultRequest.

      Set the target API URL, HTTPS method, and content of DefaultRequest. See AccessServiceImpl.java.

       public HttpResponse access(URL url, Map<String, String> headers, InputStream content, Long contentLength,
              HttpMethodName httpMethod) throws Exception {
      
              Request request = new DefaultRequest(this.serviceName);
              try {
                  request.setEndpoint(url.toURI());
              ...
              request.setHttpMethod(httpMethod);
              if (headers != null) {
                  request.setHeaders(headers);
              }
              request.setContent(content);
              ...
    3. Call the SDK signing method to sign the request.

      After the request is signed, signature information such as x-sdk-date and Authorization is added to the HTTP header of the request. See AccessServiceImpl.java.

              ...
              Signer signer = SignerFactory.getSigner(serviceName, region);
              signer.sign(request, new BasicCredentials(this.ak, this.sk));
              ...
    4. Send a request that contains the signature information.

      Convert the request signed in the previous step to a new request that can be used to call an API and copy the header of the signed request to the new request.

      For example, if Apache HttpClient is used, convert DefaultRequest to HttpRequestBase and copy the header of the signed DefaultRequest to HttpRequestBase.

      See AccessServiceImpl.java.

              ...
              HttpRequestBase httpRequestBase = createRequest(url, null, request.getContent(), contentLength, httpMethod);
              Map<String, String> requestHeaders = request.getHeaders();
      
              for (String key : requestHeaders.keySet()) {
                  if (key.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH.toString())) {
                      continue;
                  }
                  httpRequestBase.addHeader(key, requestHeaders.get(key));
              }
      
              HttpResponse response = null;
              SSLContext sslContext =
                  SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS().build();
              SSLConnectionSocketFactory sslSocketFactory =
                  new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
      
              client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
      
              response = client.execute(httpRequestBase);
              ...
      Sample code shows how to sign a request and use an HTTP client to send an HTTPS request. The code is categorized into three classes for demonstrating request signing and HTTP request sending.
      • AccessService: indicates the abstract class that converts the GET, POST, PUT, and DELETE methods into the access method.
      • Demo: indicates the execution entry used to simulate GET, POST, PUT, and DELETE request sending.
      • AccessServiceImpl: indicates the implementation of the access method. Code required for API gateway communication is in the access method.

      For details about region and serviceName in the demo code, see Regions and Endpoints.

      NOTE:
      • Parameters URI, AK, SK, and HTTP METHOD are mandatory.
      • You can use the request.addHeader() method to add header information.

      AccessService.java:

      package com.cloud.apigateway.sdk.demo;
      
      import java.io.InputStream;
      import java.net.URL;
      import java.util.Map;
      
      import org.apache.http.HttpResponse;
      
      import com.cloud.sdk.http.HttpMethodName;
      
      public abstract class AccessService {
          
          protected String serviceName = null;
          
          protected String region = null;
          
          protected String ak = null;
          
          protected String sk = null;
         
          public AccessService(String serviceName, String region, String ak, String sk) {
              this.region = region;
              this.serviceName = serviceName;
              this.ak = ak;
              this.sk = sk;
          }
          
          public abstract HttpResponse access(URL url, Map<String, String> header, InputStream content, Long contentLength,
              HttpMethodName httpMethod) throws Exception;
              
          public HttpResponse access(URL url, Map<String, String> header, HttpMethodName httpMethod) throws Exception {
              return this.access(url, header, null, 0l, httpMethod);
          }
          
          public HttpResponse access(URL url, InputStream content, Long contentLength, HttpMethodName httpMethod)
              throws Exception {
              return this.access(url, null, content, contentLength, httpMethod);
          }
          public HttpResponse access(URL url, HttpMethodName httpMethod) throws Exception {
              return this.access(url, null, null, 0l, httpMethod);
          }
          
          public abstract void close();
          
          public String getServiceName() {
              return serviceName;
          }
          
          public void setServiceName(String serviceName) {
              this.serviceName = serviceName;
          }
          
          public String getRegion() {
              return region;
          }
          
          public void setRegion(String region) {
              this.region = region;
          }
          
          public String getAk() {
              return ak;
          }
          
          public void setAk(String ak) {
              this.ak = ak;
          }
          
          public String getSk() {
              return sk;
          }
          
          public void setSk(String sk) {
              this.sk = sk;
          }
      }

      AccessServiceImpl.java:

      package com.cloud.apigateway.sdk.demo;
      
      import java.io.IOException;
      import java.io.InputStream;
      import java.net.URISyntaxException;
      import java.net.URL;
      import java.util.HashMap;
      import java.util.Map;
      
      import javax.net.ssl.SSLContext;
      
      import org.apache.http.Header;
      import org.apache.http.HttpHeaders;
      import org.apache.http.HttpResponse;
      import org.apache.http.client.methods.HttpDelete;
      import org.apache.http.client.methods.HttpGet;
      import org.apache.http.client.methods.HttpHead;
      import org.apache.http.client.methods.HttpPatch;
      import org.apache.http.client.methods.HttpPost;
      import org.apache.http.client.methods.HttpPut;
      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.entity.InputStreamEntity;
      import org.apache.http.impl.client.CloseableHttpClient;
      import org.apache.http.impl.client.HttpClients;
      
      import com.cloud.sdk.DefaultRequest;
      import com.cloud.sdk.Request;
      import com.cloud.sdk.auth.credentials.BasicCredentials;
      import com.cloud.sdk.auth.signer.Signer;
      import com.cloud.sdk.auth.signer.SignerFactory;
      import com.cloud.sdk.http.HttpMethodName;
      
      
      public class AccessServiceImpl extends AccessService {
      
       private CloseableHttpClient client = null;
      
       public AccessServiceImpl(String serviceName, String region, String ak,
         String sk) {
        super(serviceName, region, ak, sk);
       }
      
       /** {@inheritDoc} */
      
       public HttpResponse access(URL url, Map<String, String> headers,
         InputStream content, Long contentLength, HttpMethodName httpMethod)
         throws Exception {
      
        // Make a request for signing.
        Request request = new DefaultRequest(this.serviceName);
        try {
         // Set the request address.
         request.setEndpoint(url.toURI());
      
         String urlString = url.toString();
      
         String parameters = null;
      
          if (urlString.contains("?")) {
              parameters = urlString.substring(urlString.indexOf("?") + 1);
              Map parametersmap = new HashMap<String, String>();
                      
              if (null != parameters && !"".equals(parameters)) {
                          String[] parameterarray = parameters.split("&");
                          
                          for (String p : parameterarray) {
                              String key = p.split("=")[0];
                              String value = p.split("=")[1];
                              parametersmap.put(key, value);
                          }
                          request.setParameters(parametersmap);
                }
           }
      
        } catch (URISyntaxException e) {
         // It is recommended to add logs in this place. 
         e.printStackTrace();
        }
        // Set the request method.
        request.setHttpMethod(httpMethod);
        if (headers != null) {
         // Add request header information if required. 
         request.setHeaders(headers);
        }
        // Configure the request content. 
        request.setContent(content);
      
        // Select an algorithm for request signing.
        Signer signer = SignerFactory.getSigner(serviceName, region);
        // Sign the request, and the request will change after the signing.
        signer.sign(request, new BasicCredentials(this.ak, this.sk));
      
        // Make a request that can be sent by the HTTP client.
        HttpRequestBase httpRequestBase = createRequest(url, null,
          request.getContent(), contentLength, httpMethod);
        Map<String, String> requestHeaders = request.getHeaders();
        // Put the header of the signed request to the new request.
        for (String key : requestHeaders.keySet()) {
         if (key.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH.toString())) {
          continue;
         }
         httpRequestBase.addHeader(key, requestHeaders.get(key));
        }
      
        HttpResponse response = null;
        SSLContext sslContext = SSLContexts.custom()
          .loadTrustMaterial(null, new TrustSelfSignedStrategy())
          .useTLS().build();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
          sslContext, new AllowAllHostnameVerifier());
      
        client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory)
          .build();
        // Send the request, and a response will be returned.
        response = client.execute(httpRequestBase);
        return response;
       }
      
       /**
        * Make a request that can be sent by the HTTP client.
        * 
        * @param url
        *            specifies the API access path.
        * @param header
        *            specifies the header information to be added.
        * @param content
        *            specifies the body content to be sent in the API call.
        * @param contentLength
        *            specifies the length of the content. This parameter is optional.
        * @param httpMethod
        *            specifies the HTTP method to be used.
        * @return specifies the request that can be sent by an HTTP client.
        */
       private static HttpRequestBase createRequest(URL url, Header header,
         InputStream content, Long contentLength, HttpMethodName httpMethod) {
      
        HttpRequestBase httpRequest;
        if (httpMethod == HttpMethodName.POST) {
         HttpPost postMethod = new HttpPost(url.toString());
      
         if (content != null) {
          InputStreamEntity entity = new InputStreamEntity(content,
            contentLength);
          postMethod.setEntity(entity);
         }
         httpRequest = postMethod;
        } else if (httpMethod == HttpMethodName.PUT) {
         HttpPut putMethod = new HttpPut(url.toString());
         httpRequest = putMethod;
      
         if (content != null) {
          InputStreamEntity entity = new InputStreamEntity(content,
            contentLength);
          putMethod.setEntity(entity);
         }
        } else if (httpMethod == HttpMethodName.PATCH) {
         HttpPatch patchMethod = new HttpPatch(url.toString());
         httpRequest = patchMethod;
      
         if (content != null) {
          InputStreamEntity entity = new InputStreamEntity(content,
            contentLength);
          patchMethod.setEntity(entity);
         }
        } else if (httpMethod == HttpMethodName.GET) {
         httpRequest = new HttpGet(url.toString());
        } else if (httpMethod == HttpMethodName.DELETE) {
         httpRequest = new HttpDelete(url.toString());
        } else if (httpMethod == HttpMethodName.HEAD) {
         httpRequest = new HttpHead(url.toString());
        } else {
         throw new RuntimeException("Unknown HTTP method name: "
           + httpMethod);
        }
      
        httpRequest.addHeader(header);
        return httpRequest;
       }
      
       @Override
       public void close() {
        try {
         if (client != null) {
          client.close();
         }
        } catch (IOException e) {
         // It is recommended to add logs in this place. 
         e.printStackTrace();
        }
       }
      
      }

      Demo.java:

      package com.cloud.apigateway.sdk.demo;
      
      import java.io.BufferedReader;
      import java.io.ByteArrayInputStream;
      import java.io.IOException;
      import java.io.InputStream;
      import java.io.InputStreamReader;
      import java.net.MalformedURLException;
      import java.net.URL;
      
      import org.apache.http.HttpResponse;
      
      import com.cloud.sdk.http.HttpMethodName;
      
      
      public class Demo {
      
       //replace real region
       private static final String region = "regionName";
      
       //replace real service name
       private static final String serviceName = "serviceName";
      
       public static void main(String[] args) {
      
        //replace real AK
        String ak = "akString";
        //replace real SK
        String sk = "skString";
      
        // get method
        //replace real url
        String url = "urlString";
        get(ak, sk, url);
      
        // post method
        //replace real url
        String postUrl = "urlString";
        //replace real body
        String postbody = "bodyString";
        post(ak, sk, postUrl, postbody);
      
        // put method
        //replace real body
        String putbody = "bodyString";
        //replace real url
        String putUrl = "urlString";
        put(ak, sk, putUrl, putbody);
      
        // delete method
        //replace real url
        String deleteUrl = "urlString";
        delete(ak, sk, deleteUrl);
       }
      
       public static void put(String ak, String sk, String requestUrl,
         String putBody) {
      
        AccessService accessService = null;
        try {
         accessService = new AccessServiceImpl(serviceName, region, ak, sk);
         URL url = new URL(requestUrl);
         HttpMethodName httpMethod = HttpMethodName.PUT;
         
         InputStream content = new ByteArrayInputStream(putBody.getBytes());
         HttpResponse response = accessService.access(url, content,
           (long) putBody.getBytes().length, httpMethod);
         
         System.out.println(response.getStatusLine().getStatusCode());
         
        
        } catch (Exception e) {
         e.printStackTrace();
        } finally {
         accessService.close();
        }
      
       }
       
       public static void patch(String ak, String sk, String requestUrl,
         String putBody) {
      
        AccessService accessService = null;
        try {
         accessService = new AccessServiceImpl(serviceName, region, ak, sk);
         URL url = new URL(requestUrl);
         HttpMethodName httpMethod = HttpMethodName.PATCH;
         InputStream content = new ByteArrayInputStream(putBody.getBytes());
         HttpResponse response = accessService.access(url, content,
           (long) putBody.getBytes().length, httpMethod);
         
         System.out.println(convertStreamToString(response.getEntity()
           .getContent()));
        } catch (Exception e) {
         e.printStackTrace();
        } finally {
         accessService.close();
        }
      
       }
      
       public static void delete(String ak, String sk, String requestUrl) {
      
        AccessService accessService = null;
      
        try {
         accessService = new AccessServiceImpl(serviceName, region, ak, sk);
         URL url = new URL(requestUrl);
         HttpMethodName httpMethod = HttpMethodName.DELETE;
      
         HttpResponse response = accessService.access(url, httpMethod);
         System.out.println(convertStreamToString(response.getEntity()
           .getContent()));
        } catch (Exception e) {
         e.printStackTrace();
        } finally {
         accessService.close();
        }
      
       }
      
       public static void get(String ak, String sk, String requestUrl) {
      
        AccessService accessService = null;
      
        try {
         accessService = new AccessServiceImpl(serviceName, region, ak, sk);
         URL url = new URL(requestUrl);
         HttpMethodName httpMethod = HttpMethodName.GET;
         HttpResponse response;
         response = accessService.access(url, httpMethod);
         System.out.println(convertStreamToString(response.getEntity()
           .getContent()));
        } catch (Exception e) {
         e.printStackTrace();
        } finally {
         accessService.close();
        }
      
       }
      
       public static void post(String ak, String sk, String requestUrl,
         String postbody) {
      
        AccessService accessService = new AccessServiceImpl(serviceName,
          region, ak, sk);
        URL url = null;
        try {
         url = new URL(requestUrl);
        } catch (MalformedURLException e) {
         e.printStackTrace();
        }
        InputStream content = new ByteArrayInputStream(postbody.getBytes());
        HttpMethodName httpMethod = HttpMethodName.POST;
        HttpResponse response;
      
        try {
         response = accessService.access(url, content,
           (long) postbody.getBytes().length, httpMethod);
         System.out.println(convertStreamToString(response.getEntity()
           .getContent()));
        } catch (Exception e) {
         e.printStackTrace();
        } finally {
         accessService.close();
        }
       }
      
       private static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
      
        String line = null;
        try {
         while ((line = reader.readLine()) != null) {
          sb.append(line + "\n");
         }
        } catch (IOException e) {
         e.printStackTrace();
        } finally {
         try {
          is.close();
         } catch (IOException e) {
          e.printStackTrace();
         }
        }
      
        return sb.toString();
       }
      
      }

Did you find this page helpful?

Submit successfully!

Thank you for your feedback. Your feedback helps make our documentation better.

Failed to submit the feedback. Please try again later.

Which of the following issues have you encountered?







Please complete at least one feedback item.

Content most length 200 character

Content is empty.

OK Cancel