首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >鸿蒙 HarmonyOS NEXT端云一体化开发-认证服务篇

鸿蒙 HarmonyOS NEXT端云一体化开发-认证服务篇

作者头像
varin
发布2025-09-28 12:35:35
发布2025-09-28 12:35:35
13000
代码可运行
举报
文章被收录于专栏:/root/root
运行总次数:0
代码可运行

一、开通认证服务

地址:AppGallery Connect (huawei.com)

代码语言:javascript
代码运行次数:0
运行
复制
步骤:
1 进入到项目设置页面中,并点击左侧菜单中的认证服务
2 选择需要开通的服务并开通
image.png
image.png

二、端侧项目环境配置

添加依赖
代码语言:javascript
代码运行次数:0
运行
复制
entry目录下的oh-package.json5
// 添加:主要前2个依赖
"dependencies": {
    "@hw-agconnect/cloud": "^1.0.0",
    "@hw-agconnect/hmcore": "^1.0.0",
    "@hw-agconnect/auth-component": "^1.0.0", // 可选
    "long": "5.2.1"
  }
开通网络权限
代码语言:javascript
代码运行次数:0
运行
复制
// 文件名:module.json5
// 路径:src/main/module.json5
  "requestPermissions": [
      {
        "name": "ohos.permission.INTERNET" // 网络权限
      },
    ]
更新agconnect-services.json文件
代码语言:javascript
代码运行次数:0
运行
复制
// AGC网站提示:下载最新的配置文件(如果您修改了项目、应用信息或者更改了某个开发服务设置,可能需要更新该文件)
为了确保项目不会出错,建立更新下该配置文件

三 认证组件界面示例

  1. 新建Login.ets页面,并设置成为应用首页
image.png
image.png
  1. Login.ets调用认证组件
代码语言:javascript
代码运行次数:0
运行
复制
import { AuthMode, Login } from '@hw-agconnect/auth-component';
import router from '@ohos.router';


@Entry
@Component
struct MyLogin {
  @State message: string = 'Hello World';

  build() {
   Column(){
     Text("test")
     // auth-component 中的组件Login
     Login({
       modes:[AuthMode.PHONE_VERIFY_CODE] // 手机验证码登录
       ,
       onSuccess:()=>{
         //登录成功后的回调
         router.pushUrl({url:'pages/Index'})
       }

     }){
       Button("登录").height(60).width("100%")
     }


   }.width("100%").height("100%")
  }
}
image.png
image.png
image.png
image.png

四、自定义登录组件

代码语言:javascript
代码运行次数:0
运行
复制
// 参考链接:https://developer.huawei.com/consumer/cn/doc/AppGallery-connect-Guides/agc-auth-harmonyos-arkts-login-phone-0000001631566338

import cloud from '@hw-agconnect/cloud';
import { Auth, VerifyCodeAction } from '@hw-agconnect/cloud';

@Entry
@Component
struct PageTest {
  @State verificationBtnStr:string= "验证码"
  phone:string = ""
  @State verifcationBtnStatus:boolean = true
  @State timer :number = 0
  @State countDown:number = 60
  // 云端获取
  getCloudQrCode(){
    cloud.auth().requestVerifyCode({
      action: VerifyCodeAction.REGISTER_LOGIN,
      lang: 'zh_CN',
      sendInterval: 60,
      verifyCodeType: {
        phoneNumber: this.phone,
        countryCode: '86',
        kind: "phone"
      }
    }).then(verifyCodeResult => {
      //验证码申请成功
      console.log(JSON.stringify(verifyCodeResult))
      AlertDialog.show({
        title: "提示",
        message: "获取验证码成功",
      })
    }).catch((error: Promise<Result>) => {
      AlertDialog.show({
        title: "提示",
        message: "获取验证码失败",
      })
      //验证码申请失败
    });

  }
  // 初始化参数:
  initData(){
    clearInterval(this.timer)
    this.verifcationBtnStatus = true
    this.verificationBtnStr  = "验证码"
    this.countDown  = 60
  }
  // 发送验证码
  getCode(){
    if(this.phone==''){
      AlertDialog.show({
        title: "提示",
        message: "请输入手机号码",

      })
      return;
    }
    this.verifcationBtnStatus = false

    this.getCloudQrCode()


    this.timer  = setInterval(()=>{
      this.verificationBtnStr = `${this.countDown}s`
      if(this.countDown===0){
        this.initData()
        return;
      }

      this.countDown --

    },1000)
  }
  build() {
    Column({space:20}){
      TextInput({placeholder:'请输入手机号:'}).width("100%").height(60).margin({top:20})
        .onChange((value)=>{
          this.phone = value
        })
      Row(){
        TextInput({placeholder:"请输入验证码"}).layoutWeight(1).margin({right:20})
        Button(this.verificationBtnStr).width(120).onClick(()=>{
          this.getCode()

        }).enabled(this.verifcationBtnStatus)

      }.width("100%").height(60)
      Button("登录").width("100%").height(40).padding({
        left:50,right:50
      }).backgroundColor("#ff08be4b")
    }.width("100%").height("100%").padding({left:10,right:10})
  }
}
  1. 效果:
image.png
image.png

五、邮箱登录验证

代码语言:javascript
代码运行次数:0
运行
复制
import cloud from '@hw-agconnect/cloud';
import { Auth, VerifyCodeAction } from '@hw-agconnect/cloud';
import router from '@ohos.router';

@Entry
@Component
struct PageTest {
  @State verificationBtnStr:string= "验证码"
  @State phone:string = ""
  @State verifcationBtnStatus:boolean = true
  @State timer :number = 0
  @State countDown:number = 60
  @State data:string = ""
  @State verifCode:string = ""
  // 注销
  loginOut(){
    cloud.auth().signOut().then(() => {
      //登出成功
      AlertDialog.show({
        title: "提示",
        message: "注销用户成功",


      })
    }).catch(() => {
      //登出失败
    });
  }
  //登录
   login(){
   
    // 注册
     this.data = this.verifCode

     cloud.auth().signIn({
       credentialInfo: {
         kind: 'email',
         email: this.phone,
         verifyCode: this.verifCode
       }
     }).then(user => {
       //登录成功
       router.replaceUrl({url:'pages/Index'})
     }).catch((error:Promise<Result>) => {
       //登录失败
       this.data= JSON.stringify(error)
       AlertDialog.show({
         title: "提示",
         message: JSON.stringify(error),

       })
     });

  }
  // 云端获取
  getCloudQrCode(){
    cloud.auth().requestVerifyCode({
      action: VerifyCodeAction.REGISTER_LOGIN,
      lang: 'zh_CN',
      sendInterval: 60,
      verifyCodeType: {
        email: this.phone,
        kind: "email",
      }
    }).then(verifyCodeResult => {
      //验证码申请成功
      console.log(JSON.stringify(verifyCodeResult))
      this.data = JSON.stringify(verifyCodeResult)
      AlertDialog.show({
        title: "提示",
        message: "获取验证码成功",
      })
    }).catch((error: Promise<Result>) => {
      AlertDialog.show({
        title: "提示",
        message: "获取验证码失败",
      })
      //验证码申请失败
    });

  }
  // 初始化参数:
  initData(){
    clearInterval(this.timer)
    this.verifcationBtnStatus = true
    this.verificationBtnStr  = "验证码"
    this.countDown  = 60
  }
  // 发送验证码
  getCode(){
    if(this.phone==''){
      AlertDialog.show({
        title: "提示",
        message: "请输入用户邮箱",

      })
      return;
    }
    this.verifcationBtnStatus = false

    this.getCloudQrCode()


    this.timer  = setInterval(()=>{
      this.verificationBtnStr = `${this.countDown}s`
      if(this.countDown===0){
        this.initData()
        return;
      }

      this.countDown --

    },1000)
  }
  build() {
    Column({space:20}){
      TextInput({placeholder:'请输入手机号:'}).width("100%").height(60).margin({top:20})
        .onChange((value)=>{
          this.phone = value
        })
      Row(){
        TextInput({placeholder:"请输入验证码"}).layoutWeight(1).margin({right:20})
          .onChange((value)=>{
            this.verifCode =value
          })
        Button(this.verificationBtnStr).width(120).onClick(()=>{
          this.getCode()

        }).enabled(this.verifcationBtnStatus)

      }.width("100%").height(60)
      Button("登录").onClick( ()=>{
        this.data = "1aaaaaa"
        this.login()

      }).width("100%").height(40).padding({
        left:50,right:50
      }).backgroundColor("#ff08be4b")

      Button("注销").onClick( ()=>{
        this.data = "1aaaaaa"
        this.loginOut()

      }).width("100%").height(40).padding({
        left:50,right:50
      }).backgroundColor("#ff08be4b")


      Text(this.data).width("100%").height(200).backgroundColor(Color.Pink)
    }.width("100%").height("100%").padding({left:10,right:10})
  }
}
  • 获取验证码
image.png
image.png
image.png
image.png
  • 登录
image.png
image.png
代码语言:javascript
代码运行次数:0
运行
复制
// 提示用户已经登录过了,需要登出后才能重新登录
// 重而需要调用注销按钮中的登出方法
   cloud.auth().signOut()
image.png
image.png
  • 点击注销按钮
image.png
image.png
  • 点击登录后,跳转到Index页面中
image.png
image.png
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-09-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、开通认证服务
  • 二、端侧项目环境配置
  • 三 认证组件界面示例
  • 四、自定义登录组件
  • 五、邮箱登录验证
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档