当前位置: 首页 > ai >正文

【HarmonyOS6】获取华为用户信息

背景

这篇文章主要记录,个人开发者在获取华为用户授权后,拿到用户的头像和名字。获取用户的电话号码的获取需要应用获得scope权限,现仅对企业开发者开放。
在这里插入图片描述

环境配置

在项目中生成证书请求文件(CSR)

  • 在build->Generate Key and CSR中选择
    在这里插入图片描述
  • 根据下面填写内容生成CSR文件
  • 创建Key store,密码要记住的哈~~
    在这里插入图片描述
  • 输入Alias(别名)后面再项目结构配置的时候需要填写的哈,要记住。(尴尬,写到才发现单词写错了。。。)
    在这里插入图片描述
  • 保存CSR地址,点击Finish完成创建
    在这里插入图片描述

在AGC中创建项目

在这里插入图片描述

  • 在证书、APPID和Profile中创建APP
    在这里插入图片描述
  • 新建证书,然后下载证书,后续的项目配置需要使用
    在这里插入图片描述在这里插入图片描述
  • 新建Profile,并下载后续给项目配置使用

在这里插入图片描述
在这里插入图片描述

  • 在项目中添加公钥指纹,选择自己新建的公钥
    在这里插入图片描述

在项目结构中手动添加证书

  • 先查看Bundle name和AGC的项目上填写的是否一致。像我这里的,AGC是com.myapp.accentdemo,项目的是com.example.accountdemo,因此,需要先调整好Bundle name
    在这里插入图片描述

  • 在AppScope的app.json5文件中进行修改
    在这里插入图片描述
    在这里插入图片描述

  • 在Signing Configs选项卡中配置项目信息在这里插入图片描述

  • 配置Client ID,在Entry->module.json5中添加Client ID,在AGC中复制ID
    在这里插入图片描述
    在这里插入图片描述

获取用户信息代码编写

UI

  • 需要引用 authentication 和 ImageType
import { ImageType } from '@kit.UIDesignKit'
import { authentication } from '@kit.AccountKit'
import { util } from '@kit.ArkTS'@Entry
@ComponentV2
struct Index {@Local UserIcon: ImageType = $r('app.media.user_dark')@Local UserName: string = "炸鸡仔"AuthRequest?: authentication.AuthorizationWithHuaweiIDRequestbuild() {Column({ space: 10 }) {Image(this.UserIcon).width(80).height(80).borderRadius(40)Text(this.UserName).fontWeight(FontWeight.Bold).margin({ top: 5 })Button("获取用户头像和名字").width("80%").onClick(async () => {}}.height('100%').width('100%')}
}

在这里插入图片描述

获取用户信息请求对象代码

  • 通过authentication.HuaweiIDProvider().createAuthorizationWithHuaweiIDRequest()的方式创建请求对象
this.AuthRequest = new authentication.HuaweiIDProvider().createAuthorizationWithHuaweiIDRequest();// 获取头像昵称需要传如下scopethis.AuthRequest.scopes = ['profile', 'openid'];// 若开发者需要进行服务端开发,则需传如下permission获取authorizationCodethis.AuthRequest.permissions = ['serviceauthcode'];// 用户是否需要登录授权,该值为true且用户未登录或未授权时,会拉起用户登录或授权页面this.AuthRequest.forceAuthorization = false;// 用于防跨站点请求伪造this.AuthRequest.state = util.generateRandomUUID();// 用户没有授权的时候,是否弹窗提示用户授权this.AuthRequest.forceAuthorization = true;
  • 授权请求对象几个重要的属性:
    • scopes:获取用户数据,与permissions属性不能同时为空,否则会报错,默认值:[‘openid’]。其中的参数有
      • profile:华为账号用户的基本信息,如昵称头像等。
      • openid:华为账号用户的OpenID、UnionID。UnionID作为用户标识,OpenID为用户在当前应用的用户标识。
      • phone:华为账号快速验证手机号,需要scope权限,也就是企业用户哈。
      • quickLoginAnonymousPhone:获取华为账号绑定的匿名手机号,需要scope权限,也就是企业用户哈。
    • permissions:用于获取用户授权临时凭据和用户身份认证信息,与scopes属性不能同时为空。
      • serviceauthcode:用户授权临时凭据。
      • idtoken:用户身份认证信息。
    • forceAuthorization:表示华为账号未登录时,是否需要强制拉起华为账号登录页。默认值:true。
    • state:随机数并做一致性校验。该参数与响应体中返回的state比较。
    • nonce:该参数会包含在返回的ID Token中,通过校验一致性,可用于防止重放攻击。
    • idTokenSignAlgorithm:默认值:PS256,用于指定ID Token的签名算法。
    • supportAtomicService:在元服务场景下,当传入scopes包含profile时,是否支持获取用户头像昵称。如果该值为true,可以正常获取用户头像昵称。如果该值为false,执行授权请求将返回1001500003 错误代码。

获取请求数据

const controller = new authentication.AuthenticationController(this.getUIContext().getHostContext());const data: authentication.AuthorizationWithHuaweiIDResponse =await controller.executeRequest(this.AuthRequest);const authorizationWithHuaweiIDResponse = data as authentication.AuthorizationWithHuaweiIDResponse;const state = authorizationWithHuaweiIDResponse.state;if (state && this.AuthRequest.state !== state) {console.error(`Failed to authorize. The state is different, response state: ${state}`);return;}if (authorizationWithHuaweiIDResponse && authorizationWithHuaweiIDResponse.data) {//用户头像链接,有效期较短,建议先将头像下载保存后再使用,这里只是用于演示哈if (authorizationWithHuaweiIDResponse.data.avatarUri) {this.UserIcon = authorizationWithHuaweiIDResponse.data.avatarUri;}//用户昵称if (authorizationWithHuaweiIDResponse.data.nickName) {this.UserName = authorizationWithHuaweiIDResponse.data.nickName;}//唯一IDconst userUnionID = authorizationWithHuaweiIDResponse?.data?.unionID;//当前应用IDconst userOpenID = authorizationWithHuaweiIDResponse?.data?.openID;}

请求返回的结果

  • data:用户授权结果数据,可以查看SDK文档,AuthorizationWithHuaweiIDCredential
  • state:响应体中返回的state

完整代码

import { ImageType } from '@kit.UIDesignKit'
import { authentication } from '@kit.AccountKit'
import { util } from '@kit.ArkTS'@Entry
@ComponentV2
struct Index {@Local UserIcon: ImageType = $r('app.media.user_dark')@Local UserName: string = "炸鸡仔"AuthRequest?: authentication.AuthorizationWithHuaweiIDRequestbuild() {Column({ space: 10 }) {Image(this.UserIcon).width(80).height(80).borderRadius(40)Text(this.UserName).fontWeight(FontWeight.Bold).margin({ top: 5 })Button("获取用户头像和名字").width("80%").onClick(async () => {this.AuthRequest = new authentication.HuaweiIDProvider().createAuthorizationWithHuaweiIDRequest();// 获取头像昵称需要传如下scopethis.AuthRequest.scopes = ['profile', 'openid'];// 若开发者需要进行服务端开发,则需传如下permission获取authorizationCodethis.AuthRequest.permissions = ['serviceauthcode'];// 用户是否需要登录授权,该值为true且用户未登录或未授权时,会拉起用户登录或授权页面this.AuthRequest.forceAuthorization = false;// 用于防跨站点请求伪造this.AuthRequest.state = util.generateRandomUUID();// 用户没有授权的时候,是否弹窗提示用户授权this.AuthRequest.forceAuthorization = true;const controller = new authentication.AuthenticationController(this.getUIContext().getHostContext());const data: authentication.AuthorizationWithHuaweiIDResponse =await controller.executeRequest(this.AuthRequest);const authorizationWithHuaweiIDResponse = data as authentication.AuthorizationWithHuaweiIDResponse;const state = authorizationWithHuaweiIDResponse.state;if (state && this.AuthRequest.state !== state) {console.error(`Failed to authorize. The state is different, response state: ${state}`);return;}if (authorizationWithHuaweiIDResponse && authorizationWithHuaweiIDResponse.data) {//用户头像链接,有效期较短,建议先将头像下载保存后再使用,这里只是用于演示哈if (authorizationWithHuaweiIDResponse.data.avatarUri) {this.UserIcon = authorizationWithHuaweiIDResponse.data.avatarUri;}//用户昵称if (authorizationWithHuaweiIDResponse.data.nickName) {this.UserName = authorizationWithHuaweiIDResponse.data.nickName;}//唯一IDconst userUnionID = authorizationWithHuaweiIDResponse?.data?.unionID;//当前应用IDconst userOpenID = authorizationWithHuaweiIDResponse?.data?.openID;}})}.height('100%').width('100%')}
}

实现的效果如下

  • 未授权时,会有弹窗提示:
    在这里插入图片描述
  • 然后就可以显示用户头像和名字了
    在这里插入图片描述
http://www.xdnf.cn/news/14911.html

相关文章:

  • 2025年人工智能、虚拟现实与交互设计国际学术会议
  • 客户端与服务端数据加密方案及实现
  • 1️⃣理解大语言模型
  • 深度学习——损失函数
  • 使用python 将多个docx文件合并为一个word
  • 电网的智能觉醒——人工智能重构能源生态的技术革命与公平悖论
  • vue3面试题(个人笔记)
  • 并发编程第一节
  • 首批 | 云轴科技ZStack加入施耐德电气技术本地化创新生态
  • Caffeine的tokenCache与Spring的CaffeineCacheManager缓存区别
  • 一文读懂动态规划:多种经典问题和思路
  • VScode SSH远程连接Ubuntu(通过SSH密钥对的方式)
  • 深度学习遇到的问题
  • C++如何进行性能优化?
  • qt绘制饼状图并实现点击即放大点击部分
  • 前端接收流式数据demo,并用markdown解析数据,包括EventSource和fetch两种方式
  • 前端交互自定义封装类:“双回调自定义信息弹窗”
  • 香港维尔利健康科技集团AI健康云平台通过国际信息安全认证,打造全球健康数据合规新标杆
  • Transformer-BiGRU、Transformer、CNN-BiGRU、BiGRU、CNN五模型回归预测对比,Matlab代码实现
  • Ollama+OpenWebUI 0.42+0.3.35 最新版一键安装教程,解决手动更新失败问题
  • 传输层协议TCP、UDP
  • [NOIP][C++]洛谷P1376 [USACO05MAR] Yogurt factory 机器工厂
  • 实战Linux进程状态观察:R、S、D、T、Z状态详解与实验模拟
  • 智能推荐社交分享小程序(websocket即时通讯、协同过滤算法、时间衰减因子模型、热度得分算法)
  • 自动驾驶感知系统
  • 爬虫-request处理POST
  • 当DMA想“越狱”:IOMMU怎么硬核拦截?
  • c语言学习_函数递归
  • 深度学习-多分类
  • Linux网络:UDP socket创建流程与简单通信