Updated on 2024-10-10 GMT+08:00

Authentication

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.

Token-based Authentication

  • The validity period of a token is 24 hours. When using a token for authentication, cache it to prevent frequently calling the IAM API used to obtain a user token.
  • Ensure that the token is valid when you use it. Using a token that will soon expire may cause API calling failures.

A token is used to acquire temporary permissions. During API authentication using a token, the token is added to requests to get permissions for calling the API.

When calling the API for obtaining a user token, set auth.scope in the request body to project.

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

After a token is obtained, add field X-Auth-Token to the request header to specify the token when other APIs are called. For example, if the token is ABCDEFJ...., X-Auth-Token: ABCDEFJ.... can be added to a request as follows:

GET https://iam.ap-southeast-3.myhuaweicloud.com/v3.0/OS-USER/users
Content-Type: application/json
X-Auth-Token: ABCDEFJ....

AK/SK-based Authentication

You can use AK/SK to verify the identity of a request sender. In AK/SK authentication, a signature needs to be obtained and then added to requests.

AK: access key ID. It is a unique ID associated with an SK. AK is used together with SK to sign requests.

SK: secret access key. It is used together with an access key ID to identify a sender who initiates a request and to cryptographically sign requests, preventing the request from being modified.

The following uses a demo project to show how to sign a request and use an HTTP client to send an HTTPS request.

Download the demo from https://github.com/api-gate-way/SdkDemo.

Decompress the downloaded package to obtain a JAR file. Reference the extracted JAR file to the dependency path, as shown below.

  1. Create an AK/SK pair. If an AK/SK pair has already been generated, skip this step. Find the downloaded AK/SK file, which is usually named credentials.csv.

    1. Log in to the management console.
    2. Hover over the username and select My Credentials from the drop-down list.
    3. In the navigation pane, click Access Keys.
    4. Click Create Access Key.
    5. Enter your login password.
    6. Enter the verification code received by email or SMS message.

      For users created in IAM, if no email address or phone number was specified during the user creation, only a login password is required.

    7. Click OK to download the access key.

      Keep the key secure.

  2. Download and decompress the demo project.
  3. Import the demo project to Eclipse.

    Figure 1 Selecting an existing project
    Figure 2 Selecting the demo project
    Figure 3 Example structure after the demo project is imported

  4. Sign the request.

    The signature method is integrated into the JAR file imported in step 3. Sign a request before sending it. The signature will be added as part of the HTTP header of the request.

    The demo code is classified into the following classes to demonstrate:

    • AccessService: an abstract class that merges the GET, POST, PUT, and DELETE methods into the access method
    • Demo: an execution entry used to simulate GET, POST, PUT, and DELETE request sending
    • AccessServiceImpl: implements the access method, which contains the code required for communication with API Gateway.
    1. (Optional) Add a request header.
      Locate and comment out the following lines in the AccessServiceImpl.java file, and specify the project ID and account ID.
      //TODO: Add special headers. 
      //request.addHeader("X-Project-Id", "xxxxx"); 
      //request.addHeader("X-Domain-Id", "xxxxx");
    2. Edit the main method in the Demo.java file.

      Replace the bold texts with actual values. If you use other methods, such as POST, PUT, and DELETE, see the corresponding annotations.

      Specify region, serviceName, AK/SK, and URL as the actual values. In the demo, the URL for obtaining the VPC is used. Replace it with the required URL. For details on how to obtain the project ID in the URL, see Obtaining a Project ID. For details about the endpoint, see Regions and Endpoints.

      //TODO: Replace region with the name of the region in which the service to be accessed is located.
       private static final String region = ""; 
        
       //TODO: Replace serviceName with the name of the service you want to access. For example, ecs, vpc, iam, and elb. 
       private static final String serviceName = ""; 
        
       public static void main(String[] args) throws UnsupportedEncodingException 
       { 
       //TODO: Replace the AK and SK with those obtained on the My Credential page. 
       String ak = "ZIRRKMTWP******1WKNKB"; 
       String sk = "Us0mdMNHk******YrRCnW0ecfzl"; 
        
       //TODO: To specify a project ID (multi-project scenarios), add the X-Project-Id header. 
       //TODO: To access a global service, such as IAM, DNS, CDN, and TMS, add the X-Domain-Id header to specify an account ID. 
       //TODO: To add a header, find "Add special headers" in the AccessServiceImple.java file. 
        
       //TODO: Test the API 
       String url = "https://{Endpoint}/v1/{project_id}/vpcs"; 
       get(ak, sk, url); 
        
       //TODO: When creating a VPC, replace {project_id} in postUrl with the actual value. 
       //String postUrl = "https://serviceEndpoint/v1/{project_id}/cloudservers"; 
       //String postbody ="{\"vpc\": {\"name\": \"vpc\",\"cidr\": \"192.168.0.0/16\"}}"; 
       //post(ak, sk, postUrl, postbody); 
        
       //TODO: When querying a VPC, replace {project_id} in url with the actual value. 
       //String url = "https://serviceEndpoint/v1/{project_id}/vpcs/{vpc_id}"; 
       //get(ak, sk, url); 
        
       //TODO: When updating a VPC, replace {project_id} and {vpc_id} in putUrl with the actual values. 
       //String putUrl = "https://serviceEndpoint/v1/{project_id}/vpcs/{vpc_id}"; 
       //String putbody ="{\"vpc\":{\"name\": \"vpc1\",\"cidr\": \"192.168.0.0/16\"}}"; 
       //put(ak, sk, putUrl, putbody); 
        
       //TODO: When deleting a VPC, replace {project_id} and {vpc_id} in deleteUrl with the actual values. 
       //String deleteUrl = "https://serviceEndpoint/v1/{project_id}/vpcs/{vpc_id}"; 
       //delete(ak, sk, deleteUrl); 
       }
    3. Compile the code and call the API.

      In the Package Explorer area on the left, right-click Demo.java and choose Run AS > Java Application to run the demo code.

      You can view the API call logs on the console.