实现流程图
实现主要步骤
- 配置证书及权限
- 调用华为登录的 api 拉起登录界面
- 获取登录成功之后的 code(码)
- 提交给应用的后端接口
- 后端会将 code 提交给华为服务器验真
- 成功返回用户信息
- 本地拿到用户信息保存即可
获取华为登录Code
流程说明:
- 应用通过传对应scope和permission调用授权API,如果已授权则直接返回临时登录凭证Authorization Code、UnionID、OpenID,如果没有授权则拉起授权页,在用户授权后,返回Authorization Code、UnionID、OpenID。
- 将Authorization Code传给应用服务器,使用Client ID、Client Secret、Authorization Code从华为服务器中获取Access Token,再使用Access Token请求获取用户信息。
- 从用户信息中获取到手机号、UnionID、OpenID。
import { authentication } from '@kit.AccountKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { util } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';
// 创建授权请求,并设置参数
let authRequest = new authentication.HuaweiIDProvider().createAuthorizationWithHuaweiIDRequest();
// 获取手机号需要传如下scope,传参数之前需要先申请对应scope权限,才能返回对应数据
authRequest.scopes = ['phone'];
// 获取code需传如下permission
authRequest.permissions = ['serviceauthcode'];
// 用户是否需要登录授权,该值为true且用户未登录或未授权时,会拉起用户登录或授权页面
authRequest.forceAuthorization = true;
// 用于防跨站点请求伪造
authRequest.state = util.generateRandomUUID();
// 执行请求
try {
let controller = new authentication.AuthenticationController(getContext(this));
controller.executeRequest(authRequest).then((data) => {
let authorizationWithHuaweiIDResponse = data as authentication.AuthorizationWithHuaweiIDResponse;
let state = authorizationWithHuaweiIDResponse.state;
if (state != undefined && authRequest.state != state) {
hilog.error(0x0000, 'testTag', `Failed to authorize. The state is different, response state: ${state}`);
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in authentication.');
let authorizationWithHuaweiIDCredential = authorizationWithHuaweiIDResponse.data!;
let code = authorizationWithHuaweiIDCredential.authorizationCode;
let unionID = authorizationWithHuaweiIDCredential.unionID;
let openID = authorizationWithHuaweiIDCredential.openID;
// 开发者处理code、unionID、openID
}).catch((err: BusinessError) => {
this.dealAllError(err);
});
} catch (error) {
this.dealAllError(error);
}
详细代码参照快速验证