Updated on 2024-10-18 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. For details about how to obtain an endpoint, see Endpoints.

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.

A token specifies temporary permissions in a computer system. During API authentication using a token, the token is added to requests to get permissions for calling the API.

When calling the API to obtain a user token, you must set auth.scope in the request body to project.

For details about how to obtain username and domainname , see Obtaining the Account Name and Account ID. password indicates the user password.

{ 
    "auth": {
        "identity": {
            "methods": [
                "password" 
            ],
            "password": {
                "user": {
                    "name": "username", //IAM username
                    "password": "********",  //Password
                    "domain": { 
                        "name": "domainname" //Name of the account to which the IAM user belongs
                    }
                }
            }
        },
       "scope": {
            "project": { 
                "name": "xxxxxxxx" 
            }
        }
    }
}

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

GET https://iam.ap-southeast-1.myhuaweicloud.com/v3/auth/projects
Content-Type: application/json 
X-Auth-Token: ABCDEFJ....

AK/SK-based Authentication

AK/SK-based authentication and token-based authentication apply only to requests whose body size is less than 12 MB.

In AK/SK-based authentication, AK/SK is used to sign requests and the signature is then added to the requests for authentication.

  • AK: access key ID, which is a unique identifier used in conjunction with a secret access key to sign requests cryptographically.
  • SK: secret access key used in conjunction with an AK to sign requests cryptographically. It identifies a request sender and prevents the request from being modified.

In AK/SK-based authentication, you can use an AK/SK to sign a request based on the signature algorithm or use a dedicated signature SDK to sign a request. For details about how to sign requests and use the signing SDK API Request Signing Guide.

The signing SDK is only used for signing requests and is different from the SDKs provided by services.

For details about how to obtain the AK/SK, see Obtaining an AK/SK.

Demo Code

The following code shows how to sign a request and use AisAccess to send an HTTPS request:

The demo code is classified into the following classes to demonstrate signing and sending the HTTP request:

ResponseProcessUtils: tool class used to process the returned result

ImageTaggingDemo: example class of using Image Tagging. It is used to configure the AK, SK, and region parameters.

  • ResponseProcessUtils.java
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    package com.huawei.ais.demo; 
     
    import java.io.FileOutputStream; 
    import java.io.IOException; 
    import java.nio.ByteBuffer; 
    import java.nio.channels.FileChannel; 
     
    import org.apache.http.HttpResponse; 
     
    import com.alibaba.fastjson.JSON; 
    import com.alibaba.fastjson.JSONObject; 
    import com.cloud.sdk.util.Base64; 
    import com.huawei.ais.sdk.util.HttpClientUtils; 
     
    /** 
     * Tool class used to verify the information returned from service access
     */ 
    public class ResponseProcessUtils { 
         
        /** 
         * Print the HTTP status code after the service access is complete.
         *  
         * @param response Response object
         */ 
        public static void processResponseStatus(HttpResponse response) { 
            System.out.println(response.getStatusLine().getStatusCode()); 
        } 
         
        /** 
         * Convert the service access result into a character stream, which is used for displaying the JSON data.
         *  
         * @param response Response object
         * @throws UnsupportedOperationException 
         * @throws IOException 
         */ 
        public static void processResponse(HttpResponse response) throws UnsupportedOperationException, IOException { 
            System.out.println(HttpClientUtils.convertStreamToString(response.getEntity().getContent())); 
        } 
         
        /** 
         * Create the Base64-encoded image file.
         *  
         * @param response 
         * @throws UnsupportedOperationException 
         * @throws IOException 
         */ 
        public static void processResponseWithImage(HttpResponse response, String fileName) throws UnsupportedOperationException, IOException { 
            String result = HttpClientUtils.convertStreamToString(response.getEntity().getContent()); 
            JSONObject resp = JSON.parseObject(result); 
            String imageString = (String)resp.get("result"); 
            byte[] fileBytes = Base64.decode(imageString); 
            writeBytesToFile(fileName, fileBytes); 
        } 
         
        /** 
         *  Write a byte array to a file to create a binary file (for example, an image).
         * @param fileName File name
         * @param data Data
         * @throws IOException 
         */ 
        public static void writeBytesToFile(String fileName, byte[] data) throws IOException{ 
     
            FileChannel fc = null; 
            try { 
                ByteBuffer bb = ByteBuffer.wrap(data); 
                fc = new FileOutputStream(fileName).getChannel(); 
                fc.write(bb); 
                 
            } catch (Exception e) { 
                e.printStackTrace(); 
                System.out.println(e.getMessage()); 
            } 
            finally { 
                fc.close(); 
            } 
        } 
    }
    
  • ImageTaggingDemo.java
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    package com.huawei.ais.demo.image;
    
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import com.alibaba.fastjson.serializer.SerializerFeature;
    import com.huawei.ais.demo.ResponseProcessUtils;
    import com.huawei.ais.demo.ServiceAccessBuilder;
    import com.huawei.ais.sdk.AisAccess;
    import com.huawei.ais.sdk.util.HttpClientUtils;
    
    import org.apache.commons.codec.binary.Base64;
    import org.apache.commons.io.FileUtils;
    import org.apache.http.HttpResponse;
    import org.apache.http.entity.StringEntity;
    
    
    import java.io.File;
    import java.io.IOException;
    
    
    /**
     *  Example class of using Image Tagging
     */
    public class ImageTaggingDemo {
    	//
    	// Example function of using Image Tagging
    	//
    	private static void imageTaggingDemo() throws IOException {
    
    		// 1. Configure the basic information for accessing Image Tagging and generate a client connection object.
    
    		AisAccess service = ServiceAccessBuilder.builder()				
                           .ak("######")                       // your ak
                           .sk("######")                       // your sk
                           .region("ap-southeast-1")           // Configuration of Image Recognition in the CN-Hong Kong region
                           .connectionTimeout(5000)            // Timeout limit for connecting to the target URL
                           .connectionRequestTimeout(1000)     // Timeout limit for obtaining available connections from the connection pool
                           .socketTimeout(20000)               // Timeout limit for obtaining server response data
                           .build();
    
    		try {
    			//
    			// 2. Construct the parameters required for accessing Image Tagging.
    			//
    			String uri = "/v1.0/image/tagging";
    			byte[] fileData = FileUtils.readFileToByteArray(new File("data/image-tagging-demo-1.jpg"));
    			String fileBase64Str = Base64.encodeBase64String(fileData);
    			
    			JSONObject json = new JSONObject();
    			json.put("image", fileBase64Str);
    			json.put("threshold", 60);
    			StringEntity stringEntity = new StringEntity(json.toJSONString(), "utf-8");
    			
    			// 3. Pass the URI and required parameters for accessing Image Tagging.
    			// Pass the parameters in JSON objects and call the service using POST.
    			HttpResponse response = service.post(uri, stringEntity);
    			
    			// 4. Check whether the API call is successful. If 200 is returned, the API call succeeds. Otherwise, it fails.
    			ResponseProcessUtils.processResponseStatus(response);
    			
    			// 5. Process the character stream returned by the service and output the recognition result.
    			JSONObject jsonObject = JSON.parseObject(HttpClientUtils.convertStreamToString(response.getEntity().getContent()));
    			System.out.println(JSON.toJSONString(JSON.parse(jsonObject.toString()), SerializerFeature.PrettyFormat));
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    
     			// 6. Disconnect the client connection.
    			service.close();
    		}
    	}
    
    	//
    	// Main entrypoint function
    	//
    	public static void main(String[] args) throws IOException {
    		// Test entrypoint function
    		imageTaggingDemo();
    	}
    }