基于AssetStoreKit实现免密登录HarmonyOS鸿蒙Next示例代码
基于AssetStoreKit实现免密登录HarmonyOS鸿蒙Next示例代码
介绍
本示例基于Asset Store Kit关键资产存储服务提供的关键资产信息存储能力,实现了一个免密登录的场景,通过将用户的账户密码存储为关键资产信息,来实现 记住账户密码的效果,从而实现用户免密登录。
效果预览
使用说明
- 本案例功能仅能在真机上使用,测试时请使用真机。
- 使用前请设置手机锁屏密码,关键资产服务需要进行机主身份验证,需要锁屏密码。
- 运行项目前,请执行
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
更多关于基于AssetStoreKit实现免密登录HarmonyOS鸿蒙Next示例代码的实战教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
基于AssetStoreKit实现免密登录HarmonyOS鸿蒙Next的示例代码主要涉及以下几个关键步骤:
- 初始化AssetStoreKit:首先需要初始化AssetStoreKit,这是鸿蒙系统提供的一个用于存储和管理敏感数据的工具包。
import assetStoreKit from '@ohos.assetStoreKit';
assetStoreKit.init();
- 配置免密登录参数:设置免密登录所需的参数,包括用户标识、应用ID等。
const params = {
userId: 'user123',
appId: 'com.example.app',
// 其他参数
};
- 调用免密登录接口:使用AssetStoreKit提供的接口进行免密登录操作。
assetStoreKit.loginWithoutPassword(params).then((result) => {
console.log('免密登录成功:', result);
}).catch((error) => {
console.error('免密登录失败:', error);
});
- 处理登录结果:根据登录结果进行相应的处理,如跳转到主页面或显示错误信息。
if (result.code === 0) {
// 登录成功,跳转到主页面
router.push({ uri: 'pages/Home' });
} else {
// 登录失败,显示错误信息
prompt.showToast({ message: '登录失败,请重试' });
}
通过以上步骤,可以实现基于AssetStoreKit的免密登录功能,具体代码实现需根据实际应用场景进行调整。
更多关于基于AssetStoreKit实现免密登录HarmonyOS鸿蒙Next示例代码的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
以下是一个基于AssetStoreKit实现免密登录的HarmonyOS鸿蒙Next示例代码:
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.window.service.WindowManager;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.security.assetstore.AssetStoreKit;
public class MainAbility extends Ability {
private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "MainAbility");
@Override
protected void onStart(Intent intent) {
super.onStart(intent);
HiLog.info(LABEL_LOG, "MainAbility onStart");
// 初始化AssetStoreKit
AssetStoreKit assetStoreKit = new AssetStoreKit(this);
// 检查是否支持免密登录
if (assetStoreKit.isPasswordFreeSupported()) {
HiLog.info(LABEL_LOG, "Password-free login supported");
// 执行免密登录
assetStoreKit.executePasswordFreeLogin(new AssetStoreKit.PasswordFreeLoginCallback() {
@Override
public void onSuccess() {
HiLog.info(LABEL_LOG, "Password-free login success");
// 登录成功后的操作
}
@Override
public void onFail(int errorCode) {
HiLog.error(LABEL_LOG, "Password-free login failed, error code: " + errorCode);
// 登录失败后的操作
}
});
} else {
HiLog.info(LABEL_LOG, "Password-free login not supported");
}
}
}
代码说明:
- AssetStoreKit:用于实现免密登录的核心类。
- isPasswordFreeSupported():检查设备是否支持免密登录。
- executePasswordFreeLogin():执行免密登录操作,并处理成功或失败的回调。
注意事项:
- 确保设备支持免密登录功能。
- 在实际应用中,需根据业务需求处理登录成功或失败后的逻辑。