本文原创发布在华为开发者社区,更多鸿蒙场景化示例请见华为开发者联盟官网“行业实践与常见问题”专题页。

介绍

本示例基于Asset Store Kit关键资产存储服务提供的关键资产信息存储能力,实现了一个免密登录的场景,通过将用户的账户密码存储为关键资产信息,来实现 记住账户密码的效果,从而实现用户免密登录。

基于AssetStoreKit实现免密登录源码链接

效果预览

请添加链接描述

使用说明

  1. 本案例功能仅能在真机上使用,测试时请使用真机。
  2. 使用前请设置手机锁屏密码,关键资产服务需要进行机主身份验证,需要锁屏密码。
  3. 运行项目前,请执行 ohpm install @ohos/hamock,下载hamock依赖。

实现思路

在进行登录时,用户可根据需要来选择是否记住账户密码,当选择记住账户密码时,此时需要在登录时存储用户输入的账户密码,如下

static async saveAccount (accountName: string, accountPassword: string) {
  const attrInfo = AccountStoreUtils.getAccountLoginInfo(accountName, accountPassword);
  try {
    await asset.add(attrInfo);
  } catch (e) {
    hilog.error(domainId, TAG, `保存帐号失败 ${e.code} ${e.message}`);
    return;
  }

  promptAction.showToast({
    message: '已记住密码,请重新进入该页面,会自动填充账号信息'
  })
  hilog.info(domainId, TAG, `保存密码成功`)
}

账户密码信息记录完成后,下次再来登录时,根据存储的账户密码信息自动填充即可,如下:

static async queryAccountInfo (token: Uint8Array, challenge: Uint8Array) {
  const query: asset.AssetMap = new Map()
  query.set(asset.Tag.ALIAS, AccountStoreUtils.stringToBuffer(AccountStoreUtils.accountAlias))
  query.set(asset.Tag.AUTH_TOKEN, token)
  query.set(asset.Tag.AUTH_CHALLENGE, challenge)
  query.set(asset.Tag.RETURN_TYPE, asset.ReturnType.ALL)
  let accountInfo: IAccountInfo | undefined = undefined;
  try {
    const data: Array<asset.AssetMap> = await asset.query(query)
    if (data.length) {
      const map = data.shift()! as asset.AssetMap
      const secret = map.get(asset.Tag.SECRET) as Uint8Array
      accountInfo = JSON.parse(AccountStoreUtils.bufferToString(secret))
    } else {
      hilog.error(domainId, TAG, `没有查询到数据`)
    }
  } catch (e) {
    hilog.error(domainId, TAG, `查询${AccountStoreUtils.accountAlias}数据失败,错误码:${e.code},${e.message}`)
  }
  return accountInfo;
}

不过资产信息在获取前,需要进行用户的身份验证:

// step1 通过用户认证才能访问的账号信息,要先preQuery获取challenge
// step2 拉起用户认证
// step3 通过token查询数据
// step4 调用postQuery结束查询过程
static async preAccountInfo () {
  const queryInfo: asset.AssetMap = new Map()
  queryInfo.set(asset.Tag.ALIAS, AccountStoreUtils.stringToBuffer(AccountStoreUtils.accountAlias))
  // 用户认证token有效期30s
  queryInfo.set(asset.Tag.AUTH_VALIDITY_PERIOD, 30)
  try {
    // step1
    const challenge = await asset.preQuery(queryInfo)
    // step2
    AccountStoreUtils.startUserAuth(challenge)
  } catch (e) {
    hilog.error(domainId, TAG, `查询账号登录信息失败 ${e.code} ${e.message}`)
  }
}

具体代码请参考AccountStoreUtils


鸿蒙场景化代码
1 声望0 粉丝