• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Querying an Asset with User Authentication (ArkTS)
2
3## Available APIs
4
5The following table describes the APIs used for querying an asset with user authentication. For more information, see the API reference.
6
7| Asynchronous API| Synchronous API| Description|
8| ----- | ------ | ------- |
9| [preQuery(query: AssetMap)](../../reference/apis-asset-store-kit/js-apis-asset.md#assetprequery) | [preQuerySync(query: AssetMap)](../../reference/apis-asset-store-kit/js-apis-asset.md#assetprequerysync12) | Performs preprocessing.|
10| [query(query: AssetMap)](../../reference/apis-asset-store-kit/js-apis-asset.md#assetquery) | [querySync(query: AssetMap)](../../reference/apis-asset-store-kit/js-apis-asset.md#assetquerysync12) | Queries the asset.|
11| [postQuery(handle: AssetMap)](../../reference/apis-asset-store-kit/js-apis-asset.md#assetpostquery) | [postQuerySync(handle: AssetMap)](../../reference/apis-asset-store-kit/js-apis-asset.md#assetpostquerysync12) | Performs postprocessing.|
12
13The following table describes the attributes of **AssetMap** used for querying an asset with user authentication.
14
15>**NOTE**
16>
17>In the following table, the attributes starting with **DATA_LABEL** are custom asset attributes reserved for services. These attributes are not encrypted. Therefore, do not put personal data in these attributes.
18
19- **preQuery()** parameters
20
21  | Attribute Name (Tag)       | Value          | Mandatory | Description                 |
22  | --------------------- | ---------------------------| -------- | -------------------------- |
23  | ALIAS                 | Type: Uint8Array<br>Length: 1-256 bytes                           | No    | Asset alias, which uniquely identifies an asset.         |
24  | ACCESSIBILITY         | Type: number<br>Value range: see [Accessibility](../../reference/apis-asset-store-kit/js-apis-asset.md#accessibility)| No    | Access control based on the lock screen status.                                    |
25  | REQUIRE_PASSWORD_SET  | Type: Boolean                                                  | No    | Whether the asset is accessible only when a lock screen password is set. The value **true** means the asset is accessible only when a lock screen password is set. The value **false** means that the asset can be accessed regardless of whether a lock screen password is set.    |
26  | AUTH_TYPE             | Type: number<br>Value range: see [AuthType](../../reference/apis-asset-store-kit/js-apis-asset.md#authtype)| No    | Type of user authentication required for accessing the asset.                 |
27  | AUTH_VALIDITY_PERIOD  | Type: number<br>Value range: 1-600 seconds       | No    | The validity period of user authentication. The default value is **60**.         |
28  | SYNC_TYPE             | Type: number<br>Value range: see [SyncType](../../reference/apis-asset-store-kit/js-apis-asset.md#synctype)| No    | Type of sync supported by the asset.                          |
29  | IS_PERSISTENT         | Type: Boolean                                                  | No    | Whether to retain the asset when the application is uninstalled. The value **true** means to retain the asset even after the application is uninstalled. The value **false** means the opposite.              |
30  | DATA_LABEL_CRITICAL_1 | Type: Uint8Array<br>Length: 1-2048 bytes                      | No    | Asset attribute information customized by the service with integrity protection.<br>**NOTE**: The data length is 1 to 512 bytes before API version 12.|
31  | DATA_LABEL_CRITICAL_2 | Type: Uint8Array<br>Length: 1-2048 bytes                     | No    | Asset attribute information customized by the service with integrity protection.<br>**NOTE**: The data length is 1 to 512 bytes before API version 12.|
32  | DATA_LABEL_CRITICAL_3 | Type: Uint8Array<br>Length: 1-2048 bytes                       | No    | Asset attribute information customized by the service with integrity protection.<br>**NOTE**: The data length is 1 to 512 bytes before API version 12.|
33  | DATA_LABEL_CRITICAL_4 | Type: Uint8Array<br>Length: 1-2048 bytes                       | No    | Asset attribute information customized by the service with integrity protection.<br>**NOTE**: The data length is 1 to 512 bytes before API version 12.|
34  | DATA_LABEL_NORMAL_1   | Type: Uint8Array<br>Length: 1-2048 bytes                       | No    | Asset attribute information customized by the service without integrity protection.<br>**NOTE**: The data length is 1 to 512 bytes before API version 12.|
35  | DATA_LABEL_NORMAL_2   | Type: Uint8Array<br>Length: 1-2048 bytes                       | No    | Asset attribute information customized by the service without integrity protection.<br>**NOTE**: The data length is 1 to 512 bytes before API version 12.|
36  | DATA_LABEL_NORMAL_3   | Type: Uint8Array<br>Length: 1-2048 bytes                       | No    | Asset attribute information customized by the service without integrity protection.<br>**NOTE**: The data length is 1 to 512 bytes before API version 12.|
37  | DATA_LABEL_NORMAL_4   | Type: Uint8Array<br>Length: 1-2048 bytes                       | No    | Asset attribute information customized by the service without integrity protection.<br>**NOTE**: The data length is 1 to 512 bytes before API version 12.|
38  | DATA_LABEL_NORMAL_LOCAL_1<sup>12+</sup> | Type: Uint8Array<br>Length: 1-2048 bytes| No| Local attribute information about the asset. The value is assigned by the service without integrity protection and will not be synced.|
39  | DATA_LABEL_NORMAL_LOCAL_2<sup>12+</sup> | Type: Uint8Array<br>Length: 1-2048 bytes| No| Local attribute information about the asset. The value is assigned by the service without integrity protection and will not be synced.|
40  | DATA_LABEL_NORMAL_LOCAL_3<sup>12+</sup> | Type: Uint8Array<br>Length: 1-2048 bytes| No| Local attribute information about the asset. The value is assigned by the service without integrity protection and will not be synced.|
41  | DATA_LABEL_NORMAL_LOCAL_4<sup>12+</sup> | Type: Uint8Array<br>Length: 1-2048 bytes| No| Local attribute information about the asset. The value is assigned by the service without integrity protection and will not be synced.|
42  | REQUIRE_ATTR_ENCRYPTED<sup>14+</sup> | Type: Boolean| No| Whether to query the encrypted data of service customized supplementary information. The value **true** means to query the encrypted data of service customized supplementary information; the value **false** means to query the non-encrypted data of service customized supplementary information. The default value is **false**.|
43  | GROUP_ID<sup>18+</sup> | Type: Uint8Array<br>Length: 7-127 bytes| No| Group to which the asset to be queried belongs. By default, this parameter is not specified.|
44
45- **query()** parameters
46
47  | Attribute Name (Tag)       | Value                                            | Mandatory | Description                                            |
48  | --------------------- | ------------------------------------------------------------ | -------- | ------------------------------------------------ |
49  | ALIAS                 | Type: Uint8Array<br>Length: 1-256 bytes                           | Yes    | Asset alias, which uniquely identifies an asset.      |
50  | AUTH_CHALLENGE        | Type: Uint8Array<br>Length: 32 bytes                              | Yes    | Challenge for the user authentication.                             |
51  | AUTH_TOKEN            | Type: Uint8Array<br>Length: 1-1024 bytes since API version 20<br>Length: 148 bytes for API versions 11-19      | Yes    | Authorization token obtained after the user authentication is successful.                        |
52  | RETURN_TYPE           | Type: number                          | Yes    | Type of the asset query result to return.                   |
53  | ACCESSIBILITY         | Type: number<br>Value range: see [Accessibility](../../reference/apis-asset-store-kit/js-apis-asset.md#accessibility)| No    | Access control based on the lock screen status.                                    |
54  | REQUIRE_PASSWORD_SET  | Type: Boolean                                                  | No    | Whether the asset is accessible only when a lock screen password is set. The value **true** means the asset is accessible only when a lock screen password is set. The value **false** means that the asset can be accessed regardless of whether a lock screen password is set.    |
55  | AUTH_TYPE             | Type: number<br>Value range: see [AuthType](../../reference/apis-asset-store-kit/js-apis-asset.md#authtype)| No    | Type of user authentication required for accessing the asset.                 |
56  | SYNC_TYPE             | Type: number<br>Value range: see [SyncType](../../reference/apis-asset-store-kit/js-apis-asset.md#synctype)| No    | Type of sync supported by the asset.                          |
57  | IS_PERSISTENT         | Type: Boolean                                                  | No    | Whether to retain the asset when the application is uninstalled. The value **true** means to retain the asset even after the application is uninstalled. The value **false** means the opposite.    |
58  | DATA_LABEL_CRITICAL_1 | Type: Uint8Array<br>Length: 1-2048 bytes                       | No    | Asset attribute information customized by the service with integrity protection.<br>**NOTE**: The data length is 1 to 512 bytes before API version 12.|
59  | DATA_LABEL_CRITICAL_2 | Type: Uint8Array<br>Length: 1-2048 bytes                       | No    | Asset attribute information customized by the service with integrity protection.<br>**NOTE**: The data length is 1 to 512 bytes before API version 12.|
60  | DATA_LABEL_CRITICAL_3 | Type: Uint8Array<br>Length: 1-2048 bytes                       | No    | Asset attribute information customized by the service with integrity protection.<br>**NOTE**: The data length is 1 to 512 bytes before API version 12.|
61  | DATA_LABEL_CRITICAL_4 | Type: Uint8Array<br>Length: 1-2048 bytes                       | No    | Asset attribute information customized by the service with integrity protection.<br>**NOTE**: The data length is 1 to 512 bytes before API version 12.|
62  | DATA_LABEL_NORMAL_1   | Type: Uint8Array<br>Length: 1-2048 bytes                       | No    | Asset attribute information customized by the service without integrity protection.<br>**NOTE**: The data length is 1 to 512 bytes before API version 12.|
63  | DATA_LABEL_NORMAL_2   | Type: Uint8Array<br>Length: 1-2048 bytes                       | No    | Asset attribute information customized by the service without integrity protection.<br>**NOTE**: The data length is 1 to 512 bytes before API version 12.|
64  | DATA_LABEL_NORMAL_3   | Type: Uint8Array<br>Length: 1-2048 bytes                       | No    | Asset attribute information customized by the service without integrity protection.<br>**NOTE**: The data length is 1 to 512 bytes before API version 12.|
65  | DATA_LABEL_NORMAL_4   | Type: Uint8Array<br>Length: 1-2048 bytes                       | No    | Asset attribute information customized by the service without integrity protection.<br>**NOTE**: The data length is 1 to 512 bytes before API version 12.|
66  | DATA_LABEL_NORMAL_LOCAL_1<sup>12+</sup> | Type: Uint8Array<br>Length: 1-2048 bytes| No| Local attribute information about the asset. The value is assigned by the service without integrity protection and will not be synced.|
67  | DATA_LABEL_NORMAL_LOCAL_2<sup>12+</sup> | Type: Uint8Array<br>Length: 1-2048 bytes| No| Local attribute information about the asset. The value is assigned by the service without integrity protection and will not be synced.|
68  | DATA_LABEL_NORMAL_LOCAL_3<sup>12+</sup> | Type: Uint8Array<br>Length: 1-2048 bytes| No| Local attribute information about the asset. The value is assigned by the service without integrity protection and will not be synced.|
69  | DATA_LABEL_NORMAL_LOCAL_4<sup>12+</sup> | Type: Uint8Array<br>Length: 1-2048 bytes| No| Local attribute information about the asset. The value is assigned by the service without integrity protection and will not be synced.|
70  | REQUIRE_ATTR_ENCRYPTED<sup>14+</sup> | Type: Boolean| No| Whether to query the encrypted data of service customized supplementary information. The value **true** means to query the encrypted data of service customized supplementary information; the value **false** means to query the non-encrypted data of service customized supplementary information. The default value is **false**.|
71  | GROUP_ID<sup>18+</sup> | Type: Uint8Array<br>Length: 7-127 bytes| No| Group to which the asset to be queried belongs. By default, this parameter is not specified.|
72
73- **postQuery()** parameters
74
75  | Attribute Name (Tag)     | Value              | Mandatory | Description                |
76  | ------------------- | ------------------------------ | -------- | -------------------- |
77  | AUTH_CHALLENGE      | Type: Uint8Array<br>Length: 32 bytes| Yes    | Challenge for the user authentication.|
78  | GROUP_ID<sup>18+</sup> | Type: Uint8Array<br>Length: 7-127 bytes| No| Group to which the asset to be cleared belongs. By default, the assets that do not belong to any group in the memory are cleared.|
79
80## Example
81
82> **NOTE**
83>
84> The **asset** module provides asynchronous and synchronous APIs. The following uses the asynchronous APIs as an example. For more information about the APIs, see [Asset Store Service](../../reference/apis-asset-store-kit/js-apis-asset.md).
85
86Query asset **demo_alias** with user authentication. For details about **@ohos.userIAM.userAuth** used in the example, see [@ohos.userIAM.userAuth (User Authentication)](../../reference/apis-user-authentication-kit/js-apis-useriam-userauth.md#start10).
87
88```typescript
89import { asset } from '@kit.AssetStoreKit';
90import { util } from '@kit.ArkTS';
91import userAuth from '@ohos.userIAM.userAuth';
92import { BusinessError } from '@kit.BasicServicesKit';
93
94function stringToArray(str: string): Uint8Array {
95  let textEncoder = new util.TextEncoder();
96  return textEncoder.encodeInto(str);
97}
98
99function arrayToString(arr: Uint8Array): string {
100  let textDecoder = util.TextDecoder.create("utf-8", { ignoreBOM: true });
101  let str = textDecoder.decodeToString(arr, { stream: false })
102  return str;
103}
104
105async function userAuthenticate(challenge: Uint8Array): Promise<Uint8Array> {
106  return new Promise((resolve, reject) => {
107    const authParam: userAuth.AuthParam = {
108      challenge: challenge,
109      authType: [userAuth.UserAuthType.PIN],
110      authTrustLevel: userAuth.AuthTrustLevel.ATL1,
111    };
112    const widgetParam: userAuth.WidgetParam = { title:' Enter the lock screen password. '};
113    try {
114      let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
115      userAuthInstance.on('result', {
116        onResult(result) {
117          if (result.result == userAuth.UserAuthResultCode.SUCCESS) {
118            console.info(`User identity authentication succeeded.`);
119            resolve(result.token);
120          } else {
121            console.error(`User identity authentication failed.`);
122            reject();
123          }
124        }
125      });
126      userAuthInstance.start();
127    } catch (error) {
128      let err = error as BusinessError;
129      console.error(`User identity authentication failed. Code is ${err.code}, message is ${err.message}`);
130      reject();
131    }
132  })
133}
134
135function preQueryAsset(): Promise<Uint8Array> {
136  return new Promise((resolve, reject) => {
137    try {
138      let query: asset.AssetMap = new Map();
139      query.set(asset.Tag.ALIAS, stringToArray('demo_alias'));
140      asset.preQuery(query).then((challenge: Uint8Array) => {
141        resolve(challenge);
142      }).catch(() => {
143        reject();
144      })
145    } catch (error) {
146      let err = error as BusinessError;
147      console.error(`Failed to pre-query Asset. Code is ${err.code}, message is ${err.message}`);
148      reject();
149    }
150  });
151}
152
153async function postQueryAsset(challenge: Uint8Array) {
154  let handle: asset.AssetMap = new Map();
155  handle.set(asset.Tag.AUTH_CHALLENGE, challenge);
156  try {
157    await asset.postQuery(handle);
158    console.info(`Succeeded in post-querying Asset.`);
159  } catch (error) {
160    let err = error as BusinessError;
161    console.error(`Failed to post-query Asset. Code is ${err.code}, message is ${err.message}`);
162  }
163}
164
165async function queryAsset() {
166  // step1. Call asset.preQuery to obtain the challenge value.
167  preQueryAsset().then(async (challenge: Uint8Array) => {
168    try {
169      // Step 2. Pass in the challenge value to start the user authentication dialog box.
170      let authToken: Uint8Array = await userAuthenticate(challenge);
171      // Step 3 After the user authentication is successful, pass in the challenge value and authorization token to query the plaintext of the asset.
172      let query: asset.AssetMap = new Map();
173      query.set(asset.Tag.ALIAS, stringToArray('demo_alias'));
174      query.set(asset.Tag.RETURN_TYPE, asset.ReturnType.ALL);
175      query.set(asset.Tag.AUTH_CHALLENGE, challenge);
176      query.set(asset.Tag.AUTH_TOKEN, authToken);
177      let res: Array<asset.AssetMap> = await asset.query(query);
178      for (let i = 0; i < res.length; i++) {
179        // parse the secret.
180        let secret: Uint8Array = res[i].get(asset.Tag.SECRET) as Uint8Array;
181        // parse uint8array to string
182        let secretStr: string = arrayToString(secret);
183      }
184      // Step 4. After the plaintext is obtained, call asset.postQuery to perform postprocessing.
185      postQueryAsset(challenge);
186    } catch (error) {
187      // Step 5. If the operation after preQuery() fails, call asset.postQuery to perform postprocessing.
188      postQueryAsset(challenge);
189    }
190  }).catch ((err: BusinessError) => {
191    console.error(`Failed to pre-query Asset. Code is ${err.code}, message is ${err.message}`);
192  })
193}
194```
195