目录

Querying Assets Used for User Authentication (ArkTS)

Available APIs

The following table describes the APIs used for querying an asset with user authentication. For more information, see the API reference.

Asynchronous API Synchronous API Description
preQuery(query: AssetMap) preQuerySync(query: AssetMap) Performs preprocessing.
query(query: AssetMap) querySync(query: AssetMap) Queries the asset.
postQuery(handle: AssetMap) postQuerySync(handle: AssetMap) Performs postprocessing.

The following table describes the attributes of AssetMap used for querying an asset with user authentication.

In the following table, the attributes ALIAS and those starting with DATA_LABEL are custom asset attributes reserved for services. These attributes are not encrypted. Therefore, do not put sensitive personal data in these attributes.

Example

The asset module provides asynchronous and synchronous APIs. The following uses the asynchronous APIs as an example. For more information about the APIs, see @ohos.security.asset (Asset Store Service).

Before querying an asset, ensure that the asset that requires user authentication exists. For details about how to add an asset, see Adding an Asset. Otherwise, the NOT_FOUND error (24000002) is reported.

Query asset demo_alias with user authentication. For details about @ohos.userIAM.userAuth used in the example, see start in the userAuth documentation.

  1. Include the header file and define the tool function.

    import { asset } from '@kit.AssetStoreKit';
    import { util } from '@kit.ArkTS';
    import { userAuth } from '@kit.UserAuthenticationKit';
    import { BusinessError } from '@kit.BasicServicesKit';
    
    function stringToArray(str: string): Uint8Array {
      let textEncoder = new util.TextEncoder();
      return textEncoder.encodeInto(str);
    }
    
    function arrayToString(arr: Uint8Array): string {
      let textDecoder = util.TextDecoder.create('utf-8', { ignoreBOM: true });
      let str = textDecoder.decodeToString(arr, { stream: false });
      return str;
    }
  2. Develop the desired feature.

    async function userAuthenticate(challenge: Uint8Array): Promise<Uint8Array> {
      return new Promise((resolve, reject) => {
        const authParam: userAuth.AuthParam = {
          challenge: challenge,
          authType: [userAuth.UserAuthType.PIN],
          authTrustLevel: userAuth.AuthTrustLevel.ATL1,
        };
        const widgetParam: userAuth.WidgetParam = { title:' Enter the lock screen password. '};
        try {
          let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
          userAuthInstance.on('result', {
            onResult(result) {
              if (result.result == userAuth.UserAuthResultCode.SUCCESS) {
                console.info(`User identity authentication succeeded.`);
                resolve(result.token);
              } else {
                console.error(`User identity authentication failed.`);
                reject();
              }
            }
          });
          userAuthInstance.start();
        } catch (error) {
          let err = error as BusinessError;
          console.error(`User identity authentication failed. Code is ${err.code}, message is ${err.message}`);
          reject();
        }
      })
    }
    
    function preQueryAsset(): Promise<Uint8Array> {
      return new Promise((resolve, reject) => {
        try {
          let query: asset.AssetMap = new Map();
          query.set(asset.Tag.ALIAS, stringToArray('user_auth_asset'));
          asset.preQuery(query).then((challenge: Uint8Array) => {
            resolve(challenge);
          }).catch(() => {
            reject();
          })
        } catch (error) {
          let err = error as BusinessError;
          console.error(`Failed to pre-query Asset. Code is ${err.code}, message is ${err.message}`);
          reject();
        }
      });
    }
    
    async function postQueryAsset(challenge: Uint8Array) {
      let handle: asset.AssetMap = new Map();
      handle.set(asset.Tag.AUTH_CHALLENGE, challenge);
      try {
        await asset.postQuery(handle);
        console.info(`Succeeded in post-querying Asset.`);
      } catch (error) {
        let err = error as BusinessError;
        console.error(`Failed to post-query Asset. Code is ${err.code}, message is ${err.message}`);
      }
    }
    
    export async function queryUserAuthAsset(): Promise<string> {
      let result: string = '';
      // Step 1. Call asset.preQuery to obtain the challenge.
      await preQueryAsset().then(async (challenge: Uint8Array) => {
        try {
          // Step 2. Pass in the challenge to start the user authentication dialog box.
          let authToken: Uint8Array = await userAuthenticate(challenge);
          // Step 3. After the user authentication is successful, pass in the challenge and authorization token to query the plaintext of the asset.
          let query: asset.AssetMap = new Map();
          query.set(asset.Tag.ALIAS, stringToArray('user_auth_asset'));
          query.set(asset.Tag.RETURN_TYPE, asset.ReturnType.ALL);
          query.set(asset.Tag.AUTH_CHALLENGE, challenge);
          query.set(asset.Tag.AUTH_TOKEN, authToken);
          let res: asset.AssetMap[] = await asset.query(query);
          for (let i = 0; i < res.length; i++) {
            // Parse the secret.
            let secret: Uint8Array = res[i].get(asset.Tag.SECRET) as Uint8Array;
            // Convert Uint8Array into the string type.
            let secretStr: string = arrayToString(secret);
          }
          // Step 4. After the plaintext is obtained, call asset.postQuery to perform postprocessing.
          postQueryAsset(challenge);
          result = 'Succeeded in querying user-auth Asset';
        } catch (error) {
          // Step 5. If the operation after preQuery() fails, call asset.postQuery to perform postprocessing.
          postQueryAsset(challenge);
          result = 'Failed to query user-auth Asset';
        }
      }).catch((err: BusinessError) => {
        console.error(`Failed to pre-query Asset. Code is ${err.code}, message is ${err.message}`);
        result = 'Failed to query user-auth Asset';
      })
      return result;
    }