Overview

Auth Service provides cloud services and an SDK to help you quickly build a secure and reliable user authentication system for your app. It supports multiple authentication modes and is closely integrated with other serverless services for you to effectively protect user data by defining simple rules.
By integrating the Auth Service SDK, you can connect to multiple third-party user authentication systems, such as HUAWEI ID, WeChat, Facebook, and Twitter, and report authentication credentials to the AppGallery Connect Auth Service server. When a user signs in to an app again, the app can obtain user information and other data protected by security rules in other serverless services from Auth Service.
Auth Service can greatly reduce your investment and costs in building an authentication system and its O&M.

What You Will Create

In this codelab, you will build a web app that integrates Auth Service to authenticate sign-ins. Your app will allow users to:

What You Will Learn

Development Environment and Skill Requirements

To integrate Auth Service of AppGallery Connect, you must complete the following preparations:

For details, please refer to Integration Preparations.
  1. Sign in to AppGallery Connect, click My projects, click your project card, and select your app for which you want to enable Auth Service from the drop-down list on the top. Go to Build > Auth Service. If it is the first time that you use Auth Service, click Enable now in the upper right corner.
  2. Click Enable for each authentication mode you want to enable. In this codelab, click Enable for Mobile number and Anonymous account.

Run the following command to integrate the Auth Service JavaScript SDK into your project, and add the dependency to the package.json file:

npm install --save @agconnect/auth@1.2.1

You can design the UI according to the following figure, with simple entries for users to sign in anonymously or using a mobile number.

In this codelab, the third-party open-source layout library based on Element UI is used. You need to import the tool first.

  1. Add the Element UI dependency to dependencies in the package.json file.
    "element-ui": "^2.13.2"
  2. Open the main.js file and import Element UI.
    import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(ElementUI)
  3. Create the login.vue file for the sign-in page and add the corresponding layout to the file.
    Sample code:
    <template> <div class="login-container"> <el-form :model="dataForm_sdk" :rules="rules" status-icon label-position="left" label-width="0px" class="demo-ruleForm login-page"> <h3 class="title">Auth Service Codelab</h3> <el-form-item prop="account"> <el-input type="text" v-model="dataForm_sdk.account" auto-complete="off" placeholder="Account"></el-input> </el-form-item> <el-form-item prop="password"> <el-input type="password" v-model="dataForm_sdk.password" auto-complete="off" placeholder="Password"></el-input> </el-form-item> <el-form-item prop="verifyCode"> <el-input type="text" v-model="dataForm_sdk.verifyCode" auto-complete="off" placeholder="PIN"> <el-button slot="suffix" type="info" size="mini" @click="getVerifyCode">get PIN</el-button> </el-input> </el-form-item> <br/> <el-form-item style="width: 100%;"> <el-row> <el-button type="primary" size="medium" style="width: 28%;" @click="loginByPwd">login by PWD</el-button> <el-button type="primary" size="medium" style="width: 28%;" @click="loginByVerifyCode">login by PIN </el-button> <el-button type="primary" size="medium" style="width: 36%;" @click="loginAnonymously">login anonymously </el-button> </el-row> <br/> <el-row> <el-button type="success" size="medium" style="width: 28%;" @click="createUser" round>create user</el-button> </el-row> <br/> <el-collapse accordion> <el-collapse-item> <template slot="title">User info</template> <el-form :label-position="labelPosition" style="width: 20%;" label-width="120px" :model="accountInfo"> <el-form-item label="UID:">{{ accountInfo.uid }}</el-form-item> <el-form-item label="Anonymous:">{{ accountInfo.anonymous }}</el-form-item> <el-form-item label="displayName:">{{ accountInfo.displayName }}</el-form-item> <el-form-item label="email:">{{ accountInfo.email }}</el-form-item> <el-form-item label="phone:">{{ accountInfo.phone }}</el-form-item> <el-form-item label="photoUrl:">{{ accountInfo.photoUrl }}</el-form-item> <el-form-item label="providerId:">{{ accountInfo.providerId }}</el-form-item> <el-form-item label="emailVerified:">{{ accountInfo.emailVerified }}</el-form-item> <el-form-item label="passwordSetted:">{{ accountInfo.passwordSetted }}</el-form-item> </el-form> <br/><br/> <el-button type="primary" size="medium" style="width: 50%;" @click="logOut">log out</el-button> <br/><br/> <el-button type="danger" size="medium" style="width: 50%;" @click="deleteUser">delete user</el-button> </el-collapse-item> </el-collapse> </el-form-item> </el-form> </div> </template>

    The code in style is as follows:

    <style scoped> .login-container { width: 100%; height: 100%; } .login-page { -webkit-border-radius: 5px; border-radius: 5px; margin: 60px auto; width: 420px; padding: 35px 35px 15px; background: #fff; border: 1px solid #eaeaea; box-shadow: 0 0 25px #cac6c6; } label.el-checkbox.remember { margin: 0px 0px 15px; text-align: left; } </style>
  1. Import dependencies required by Auth Service to the vue.js file.
    import agconnect from "@agconnect/api"; import "@agconnect/auth"; import "@agconnect/instance";
  2. Define parameters required by your app and add them to the data block of export default.
    data () { return { provider: 'phone', customProvider: '0', dataForm_sdk: { account: '', password: '', verifyCode: '', }, accountInfo: { uid: '', anonymous: '', displayName: '', email: '', phone: '', photoUrl: '', providerId: '', emailVerified:'', passwordSetted:'', }, rules: { email: [{required: true, message: 'input your account', trigger: 'blur'}], password: [{required: false, message: 'input your password', trigger: 'blur'}], }, labelPosition: 'left', value: '' }; },
  3. Add parameters for SDK initialization to the created method. Copy app file information.
    async created() { var agConnectConfig = { // App configurations. }; agconnect.instance().configInstance(agConnectConfig); },
  4. Call the getCurrentUser method of the SDK to obtain user information during app launch.
    getUserInfo() { agconnect.auth().getCurrentUser().then((user) => { if (user) { this.accountInfo.anonymous = user.isAnonymous(); this.accountInfo.uid = user.getUid(); this.accountInfo.displayName = user.getDisplayName(); this.accountInfo.email = user.getEmail(); this.accountInfo.phone = user.getPhone(); this.accountInfo.photoUrl = user.getPhotoUrl(); this.accountInfo.providerId = user.getProviderId(); this.accountInfo.emailVerified = user.getEmailVerified(); this.accountInfo.passwordSetted = user.getPasswordSetted(); } else { this.accountInfo.anonymous = ""; this.accountInfo.uid = ""; this.accountInfo.displayName = ""; this.accountInfo.email = ""; this.accountInfo.phone = ""; this.accountInfo.photoUrl = ""; this.accountInfo.providerId = ""; this.accountInfo.emailVerified = ""; this.accountInfo.passwordSetted = ""; } }).catch((err) => { console.error("getuserinfo err:", err); }); },
  5. Develop a sign-in using a mobile number. First, call the requestVerifyCode method to request a verification code for registration.
    getVerifyCode() { agconnect.auth.PhoneAuthProvider.requestVerifyCode('86', this.dataForm_sdk.account, agconnect.auth.Action.ACTION_REGISTER_LOGIN,'zh_CN', 90) .then((ret) => { alert('verify code sent by AGC!'); }).catch((err) => { alert(JSON.stringify(err)); }); },
  6. After obtaining the verification code, click create user for registration. After the registration is successful, the user is signed in automatically, and your app does not need to call the sign-in API.
    createUser() { agconnect.auth().createPhoneUser(new agconnect.auth.PhoneUser( '86', this.dataForm_sdk.account, this.dataForm_sdk.verifyCode, this.dataForm_sdk.password), ).then((res) => { alert('create user successfully!'); this.getUserInfo(); }).catch((err) => { alert(JSON.stringify(err)); }); },
  7. If a registered user needs to sign in, add code as follows to sign in the user using a password or a verification code:
    • Signing In with a Password
    • loginByPwd() { if (this.dataForm_sdk.password == '') { alert('Please input password!'); return; } let credential = agconnect.auth.PhoneAuthProvider.credentialWithPassword('86', this.dataForm_sdk.account, this.dataForm_sdk.password) agconnect.auth().signIn(credential) .then((res) => { alert('login successfully!'); this.getUserInfo(); }).catch((err) => { alert(err); }); },
    • Signing In with a Verification Code
      loginByVerifyCode() { if (this.dataForm_sdk.verifyCode == '') { alert('Please input verifyCode!'); return; } let credential = agconnect.auth.PhoneAuthProvider.credentialWithVerifyCode('86', this.dataForm_sdk.account, this.dataForm_sdk.password, this.dataForm_sdk.verifyCode) agconnect.auth().signIn(credential).then((res) => { alert('login successfully!'); this.getUserInfo(); }).catch((err) => { alert(JSON.stringify(err)); }); },
  8. You can also call the anonymous sign-in API to sign in a user anonymously.
    loginAnonymously() { agconnect.auth().signInAnonymously().then((res) => { alert('login successfully!'); this.getUserInfo(); }).catch((err) => { alert(JSON.stringify(err)); }); },
  9. To sign out a user from your app or deregister a user, call the related API.
    • Sign-out
    • logOut() { agconnect.auth().signOut().then(() => { alert('log out!'); this.accountInfo = { uid: '', anonymous: '', displayName: '', email: '', phone: '', photoUrl: '', providerId: '', emailVerified: '', passwordSetted: '', }; }).catch((err) => { alert(JSON.stringify(err)); }); },
    • Deregistration
      deleteUser() { this.$confirm('Permanently delete current user, continue?', 'Tips', { confirmButtonText: 'YES', cancelButtonText: 'NO', type: 'warning', }).then(async () => { await agconnect.auth().deleteUser().then(() => { alert('delete User OK') this.accountInfo = { uid: '', anonymous: '', displayName: '', email: '', phone: '', photoUrl: '', providerId: '', emailVerified: '', passwordSetted: '', }; }); }).catch((err) => { alert(JSON.stringify(err)); }); },
  1. Run the following command on the Terminal tab page in IntelliJ IDEA:
    npm start

After the compilation is complete, click the generated link.

  1. Enter the mobile number and password, and then click get PIN.
  2. After obtaining the verification code, enter it and click create user to create a user.
  3. Open the User info page to view the user information.
  4. Click log out to sign out.
  5. Click login anonymously to sign in the user anonymously.
  6. Repeat step 4 to check whether anonymous user information exists. If the sign-in is successful, anonymous user information will be displayed.

Well done. You have successfully built an app that integrates Auth Service of AppGallery Connect and learned how to build a user authentication system using the service.

API Reference
You can download the sample code in this codelab.

Code copied