当前位置:网站首页>Rapid integration of authentication services - harmonyos platform

Rapid integration of authentication services - harmonyos platform

2022-07-07 08:35:00 Huawei Developer Forum

   We can integrate authentication services in applications SDK To easily and quickly launch registration to users 、 Login and other related functions . Here's how to use HarmonyOS Platform integration AGC Certification services .

Integrated content

adopt harmony sdk Plug in integration AGC The validation service , stay AGC Start the authentication service on , And add two ways of mobile phone verification and email verification , At the same time, end-to-side integration SDK Called by AGC Send verification code to mobile phone or email , Enter the verification code and password to complete user registration .

Integration preparation

  1. install DevEco Studio development tool , And be familiar with Harmony Application development process .
  2. AGC Create projects and open services .

        a) stay AGC establish Harmony Apply and open the verification service .

cke_202.png

cke_203.png

Enable mobile phone and email authentication

cke_204.png

3、DevEco Studio Created in Harmony engineering

     a) open IDE Tools , choice File-New-New project, choice Java After the language compiles the template , Click on Next Enter the create project configuration interface .

cke_205.png

Pay attention to the application (Application), Package name and AGC The application package name created is the same .

cke_206.png

 

  b) take agconnect-services.json Copy the file to the project's entry Module directory

cke_207.png

c) To configure Maven Warehouse address and AGC Plug-in address .

  open harmony Project level build.gradle file .

  stay allprojects ->repositories It's equipped with maven Warehouse address .

  stay buildscript->repositories Middle configuration maven Warehouse address .

  stay buildscript->dependencies Middle configuration AppGallery Connect Plug-in address .

The test environment needs to configure the internal private warehouse address , Formal environment requires configuration of external formal warehouse .

buildscript {    repositories {        maven {            url 'https://repo.huaweicloud.com/repository/maven/'        }        maven {            url 'https://developer.huawei.com/repo/'        }        maven { url 'http://language.cloudartifact.dgg.dragon.tools.huawei.com/artifactory/product_maven' }        maven { url 'http://szg1.artifactory.inhuawei.com/artifactory/sz-maven-public/' }        jcenter()    }    dependencies {        classpath 'com.huawei.ohos:hap:2.4.4.2'        classpath 'com.huawei.ohos:decctest:1.2.4.0'        classpath 'com.huawei.agconnect:agcp-harmony:1.2.0.200'    }}allprojects {    repositories {        maven {            url 'https://repo.huaweicloud.com/repository/maven/'        }        maven {            url 'https://developer.huawei.com/repo/'        }        maven { url 'http://language.cloudartifact.dgg.dragon.tools.huawei.com/artifactory/product_maven' }        maven { url 'http://szg1.artifactory.inhuawei.com/artifactory/sz-maven-public/' }        jcenter()    }}

d) Add compilation dependencies and integrations SDK.

open harmony Project application level (entry) Of build.gradle file , Add plug-in address .

apply plugin: 'com.huawei.ohos.hap'apply plugin: 'com.huawei.ohos.decctest'apply plugin: 'com.huawei.agconnect'

stay “dependencies” Add... To agconnect-core Compilation dependencies and crash SDK.

dependencies {    implementation fileTree(dir: 'libs', include: ['*.jar', '*.har'])    implementation 'com.huawei.agconnect:agconnect-auth-harmony:1.2.0.1-snapshot'    implementation 'com.huawei.agconnect:agconnect-tasks-harmony:1.2.0.1-snapshot'}

e)entry (hap) Add configuration information to the module

enrty Modular config.json Of documents module/abilities in , Add the following configuration , Pay attention to the replacement of package name .

{  "permissions": [    "com.huawei.agconnect.core.DataAbilityShellProvider.PROVIDER"  ],  "name": "com.huawei.agconnect.core.provider.AGConnectInitializeAbility",  "type": "data",  "uri": "dataability://com.huawei.agconnect.auth.AGConnectInitializeAbility"}

f) Synchronize project configuration

1.png

4、 Configure signature information

Harmony Install the application to the real machine for testing , Signature information needs to be configured , There are two ways of manual signature and automatic signature , For details, please refer to : Configure signature information . It is recommended to give priority to automatic signature , If the automatic signature fails , You can choose to sign manually . Here we use automatic signature :

    a) Connect real equipment , Make sure DevEco Studio Connected to the real device , After the real machine is successfully connected, it is shown in the following figure

    image.png

      b) Get into File > Project Structure > Project > Signing Configs Interface , Click on “Sign In” Button to log in , choice Debug, Check Automatically generate signing, Click on try again You can automatically sign . Automatically generate the key required for signature (.p12)、 digital certificate (.cer) and Profile file (.p7b) Will be saved to the user user In the catalog .ohos\config Under the table of contents .

      image.png

      After setting the signature information , Click on OK Preservation , Then you can do it under the project build.gradle View signature configuration information in .

      image.png

      Sign in AGC, Get into “ Users and access ”-“ Certificate management ”, Click Add certificate , Upload the previously generated .csr file , Type selection commissioning certificate

      After completing the signature configuration, you can click Install to apply to the debugging device .

      Function realization

      Mobile authentication login layout design

      image.png

      Refer to the layout above , Enter the country code in the four text boxes 、 cell-phone number 、 password 、 Verification Code , Click to verify and receive the verification code SMS , Enter verification code , Click login , Complete registration and login The layout code is as follows :

      <?xml version="1.0" encoding="utf-8"?><DirectionalLayout    xmlns:ohos="http://schemas.huawei.com/res/ohos"    ohos:width="match_parent"    ohos:height="match_parent">    <TextField        ohos:id="$+id:countryCode"        ohos:height="match_content"        ohos:width="150vp"        ohos:hint="Your countryCode"        ohos:text_input_type="pattern_number"        ohos:text_size="50"        ohos:top_margin="10vp"        />    <TextField        ohos:id="$+id:phoneNumber"        ohos:height="match_content"        ohos:width="150vp"        ohos:hint="Your phone"        ohos:text_input_type="pattern_number"        ohos:text_size="50"        ohos:bottom_margin="10vp"        />    <TextField        ohos:id="$+id:password"        ohos:height="match_content"        ohos:width="150vp"        ohos:hint="Password"        ohos:text_input_type="pattern_password"        ohos:text_size="50"        ohos:bottom_margin="10vp"        />    <TextField        ohos:id="$+id:verifyCode"        ohos:height="match_content"        ohos:width="150vp"        ohos:hint="verifyCode"        ohos:text_input_type="pattern_number"        ohos:text_size="50"        ohos:bottom_margin="10vp"        />    <DirectionalLayout        ohos:height="match_content"        ohos:width="match_parent"        ohos:orientation="horizontal">        <Button            ohos:id="$+id:Verify"            ohos:height="match_content"            ohos:width="100vp"            ohos:background_element="$graphic:background_ability_main"            ohos:left_margin="15vp"            ohos:text="Verify"            ohos:text_size="16fp"/>        <Button            ohos:id="$+id:Login"            ohos:height="match_content"            ohos:width="100vp"            ohos:background_element="$graphic:background_ability_main"            ohos:left_margin="15vp"            ohos:text="Login"            ohos:text_size="16fp"/>    </DirectionalLayout></DirectionalLayout>

      Authentication and login :

      Enter the country code 、 cell-phone number 、 Then click Verify, Return the verification code sending success log , The mobile phone receives the verification code , Enter the password and verification code and click Login Return the login success log :

      image.png

      The page jumps to the login success page :

      image.png

      The authentication and login codes are as follows :

      private void verify() {    String countryCode = getCountryCode();    String phoneNumber = getPhoneNumber();    int action = VerifyCodeSettings.ACTION_REGISTER_LOGIN;    VerifyCodeSettings settings = VerifyCodeSettings.newBuilder()            .action(action)            .sendInterval(30)            .build();    HarmonyTask<VerifyCodeResult> task = AGConnectAuth.getInstance()            .requestVerifyCode(countryCode, phoneNumber, settings);    task.addOnSuccessListener(TaskExecutors.uiThread(), new OnSuccessListener<VerifyCodeResult>() {        @Override        public void onSuccess(VerifyCodeResult verifyCodeResult) {            log("verifyPhoneCode success");        }    }).addOnFailureListener(TaskExecutors.uiThread(), new OnFailureListener() {        @Override        public void onFailure(Exception e) {            log("verifyPhoneCode fail:" + e);        }    });}private void login() {    String countryCode = getCountryCode();    String phoneNumber = getPhoneNumber();    String password = getPassword();    String verifyCode = getVerify();    AGConnectAuthCredential phoneAuthCredential =            PhoneAuthProvider.credentialWithVerifyCode(countryCode, phoneNumber, password, verifyCode);    /* signIn */    HarmonyTask<SignInResult> task = AGConnectAuth.getInstance().signIn(phoneAuthCredential);    task.addOnSuccessListener(new OnSuccessListener<SignInResult>() {        @Override        public void onSuccess(SignInResult signInResult) {            log("signIn success");            showUser(signInResult.getUser());        }    }).addOnFailureListener(new OnFailureListener() {        @Override        public void onFailure(Exception e) {            log("signInWithCode fail:" + e);        }    });}

      2、 Mailbox verification login layout

      image.png

      Refer to the layout above , Enter the mailbox number in the three text boxes 、 password 、 Verification Code , Click to verify and receive the verification code SMS , Enter verification code , Click login , Complete registration and login , The layout code is as follows :

      <?xml version="1.0" encoding="utf-8"?><DirectionalLayout    xmlns:ohos="http://schemas.huawei.com/res/ohos"    ohos:width="match_parent"    ohos:height="match_parent">        <TextField        ohos:id="$+id:phoneNumber"        ohos:height="match_content"        ohos:width="150vp"        ohos:hint="Your phone"        ohos:text_input_type="pattern_number"        ohos:text_size="50"        ohos:bottom_margin="10vp"        />    <TextField        ohos:id="$+id:password"        ohos:height="match_content"        ohos:width="150vp"        ohos:hint="Password"        ohos:text_input_type="pattern_password"        ohos:text_size="50"        ohos:bottom_margin="10vp"        />    <TextField        ohos:id="$+id:verifyCode"        ohos:height="match_content"        ohos:width="150vp"        ohos:hint="verifyCode"        ohos:text_input_type="pattern_number"        ohos:text_size="50"        ohos:bottom_margin="10vp"        />    <DirectionalLayout        ohos:height="match_content"        ohos:width="match_parent"        ohos:orientation="horizontal">        <Button            ohos:id="$+id:Verify"            ohos:height="match_content"            ohos:width="100vp"            ohos:background_element="$graphic:background_ability_main"            ohos:left_margin="15vp"            ohos:text="Verify"            ohos:text_size="16fp"/>        <Button            ohos:id="$+id:Login"            ohos:height="match_content"            ohos:width="100vp"            ohos:background_element="$graphic:background_ability_main"            ohos:left_margin="15vp"            ohos:text="Login"            ohos:text_size="16fp"/>    </DirectionalLayout></DirectionalLayout>

      Enter the email number and click Verify, Return the verification code sending success log , Email received verification code , Enter the password and verification code and click Login Return the login success log :

      image.png

      The page jumps to the login success page :

      image.png

      The email verification and login codes are as follows :

      private void verify() {    //String countryCode = getCountryCode();    String emailStr = getEmailStr();    int action = VerifyCodeSettings.ACTION_REGISTER_LOGIN;    VerifyCodeSettings settings = VerifyCodeSettings.newBuilder()            .action(action)            .sendInterval(30)            .build();    HarmonyTask<VerifyCodeResult> task = AGConnectAuth.getInstance()            .requestVerifyCode(emailStr, settings);    task.addOnSuccessListener(TaskExecutors.uiThread(), new OnSuccessListener<VerifyCodeResult>() {        @Override        public void onSuccess(VerifyCodeResult verifyCodeResult) {            log("verifyEmailCode success");        }    }).addOnFailureListener(TaskExecutors.uiThread(), new OnFailureListener() {        @Override        public void onFailure(Exception e) {            log("verifyEmailCode fail:" + e);        }    });}private void login() {    //String countryCode = getCountryCode();    String emailStr = getEmailStr();    String password = getPassword();    String verifyCode = getVerify();    AGConnectAuthCredential emailAuthCredential =            EmailAuthProvider.credentialWithVerifyCode(emailStr, password, verifyCode);    /* signIn */    HarmonyTask<SignInResult> task = AGConnectAuth.getInstance().signIn(emailAuthCredential);    task.addOnSuccessListener(new OnSuccessListener<SignInResult>() {        @Override        public void onSuccess(SignInResult signInResult) {            log("signIn success");            showUser(signInResult.getUser());        }    }).addOnFailureListener(new OnFailureListener() {        @Override        public void onFailure(Exception e) {            log("signInWithCode fail:" + e);        }    });}

      A functional test

      After landing successfully , open AGC The validation service , Query data in the background :

      Users who register with mobile phones and e-mail all display account information and authentication times in the background , The number of verifications is the same as the number of requests ;

      image.png

      image.png

      stay AGC Delete account on , If you log in again with the same user name and password, you will report that the user name or password is wrong

      image.png

      After disabling the account, login will report that the account has been disabled .

      image.png

       

      For more technical articles , Welcome to visit https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh
       

      原网站

      版权声明
      本文为[Huawei Developer Forum]所创,转载请带上原文链接,感谢
      https://yzsam.com/2022/188/202207070537375409.html