实现华为授权登录

实现流程图

实现主要步骤

  1. 配置证书及权限
  2. 调用华为登录的 api 拉起登录界面
  3. 获取登录成功之后的 code(码)
  4. 提交给应用的后端接口
  5. 后端会将 code 提交给华为服务器验真
  6. 成功返回用户信息
  7. 本地拿到用户信息保存即可

获取华为登录Code

流程说明:

  1. 应用通过传对应scope和permission调用授权API,如果已授权则直接返回临时登录凭证Authorization Code、UnionID、OpenID,如果没有授权则拉起授权页,在用户授权后,返回Authorization Code、UnionID、OpenID。
  2. 将Authorization Code传给应用服务器,使用Client ID、Client Secret、Authorization Code从华为服务器中获取Access Token,再使用Access Token请求获取用户信息。
  3. 从用户信息中获取到手机号、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);
}

详细代码参照快速验证

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值