Auth Service provides cloud services and an SDK to help you quickly build a secure and reliable user authentication system for your app. Auth Service supports multiple authentication modes and is closely integrated with other serverless functions, effectively protecting user data by defining simple rules.
By integrating the Auth Service SDK, you can connect to user authentication systems of multiple third parties, such as HUAWEI ID, WeChat, Facebook, and Twitter, and report authentication credentials to the AppGallery Connect Auth Service cloud. When a user signs in to an app again, the app can obtain the user's personal information and other data protected by security rules in other serverless functions 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 an Android app that integrates Auth Service to authenticate sign-ins. Your app will allow users to:

What You Will Learn

Development Environment and Skill Requirements

Device Requirements

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

For details, please refer to Preparations for Integration in AppGallery Connect.

Enabling Auth Service

  1. Click My projects in AppGallery Connect and click the app for which you need to enable Auth Service on the project card. 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 in the row of each authentication mode to be enabled. In this codelab, click Enable for Mobile number and Anonymous account.

Integrating the Auth Service SDK

If you are using Android Studio, you can integrate the Auth Service SDK by using the Maven repository into your Android Studio project before development.

  1. Click My projects in AppGallery Connect and click the app for which you need to enable Auth Service on the project card.
  2. Go to Project Settings > General information. In the App information area, download the agconnect-services.json file.
  3. Copy the agconnect-services.json file to the app's root directory.
  4. Open the app-level build.gradle file and add the following code to integrate the Auth SDK:
    // Configure the following address: apply plugin: 'com.huawei.agconnect' dependencies { // Configure the following address: implementation 'com.huawei.agconnect:agconnect-auth:' }
  5. Click Sync Now to synchronize the configuration.

You can create a page in your Android Studio project and design the UI according to the following figure, with simple entries for users to sign in anonymously or using a mobile number.

  1. Sign in anonymously. After the sign-in is successful, UID of the current user is generated to TextView, for subsequent comparison.
    public void anonymousLogin() { AGConnectAuth.getInstance().signInAnonymously().addOnSuccessListener(new OnSuccessListener<SignInResult>() { @Override public void onSuccess(SignInResult signInResult) { AGConnectUser user = signInResult.getUser(); String uid = user.getUid(); anonymousResult.setText("Uid: " + uid); anonymousResult.setVisibility(View.VISIBLE); Log.i(TAG, "UidValue: " + uid); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { anonymousResult.setText("Anonymous SignIn failed"); anonymousResult.setVisibility(View.VISIBLE); Log.e(TAG, "UidValue: " + e.getMessage()); } }); }
  2. Enter the country code and mobile number in EditText and click the button for obtaining the verification code. The SDK requests a verification code from the Auth Service server and enters the received verification code in EditText.
    public void sendVerifCode() { VerifyCodeSettings settings = VerifyCodeSettings.newBuilder() .action(VerifyCodeSettings.ACTION_REGISTER_LOGIN) .sendInterval(30) // Shortest sending interval, 30–120s .locale(Locale.SIMPLIFIED_CHINESE) //optional,must contain country and language eg:zh_CN .build(); String countCode = countryCode.getText().toString().trim(); String phoneNumber = phoneNumeber.getText().toString().trim(); if (notEmptyString(countCode) && notEmptyString(phoneNumber)) { Task<VerifyCodeResult> task = PhoneAuthProvider.requestVerifyCode(countCode, phoneNumber, settings); task.addOnSuccessListener(TaskExecutors.uiThread(), new OnSuccessListener<VerifyCodeResult>() { @Override public void onSuccess(VerifyCodeResult verifyCodeResult) { Toast.makeText(MainActivity.this, "verify code has been sent.", Toast.LENGTH_SHORT).show(); } }).addOnFailureListener(TaskExecutors.uiThread(), new OnFailureListener() { @Override public void onFailure(Exception e) { Toast.makeText(MainActivity.this, "Send verify code failed.", Toast.LENGTH_SHORT).show(); Log.e(TAG, "requestVerifyCode fail:" + e); } }); } else { Toast.makeText(MainActivity.this, "Please enter the phone number and country code", Toast.LENGTH_SHORT).show(); } }
  3. Bind a mobile number and use the country code, mobile number, and received verification code to construct the credential required for associating with the account.
    String phoneNumber = phoneNumeber.getText().toString().trim(); String countCode = countryCode.getText().toString().trim(); String verifyCode = verfiCode.getText().toString().trim(); // Sign-in logic. AGConnectAuthCredential credential = PhoneAuthProvider.credentialWithVerifyCode( countCode, phoneNumber, null, // password, can be null verifyCode);
  4. Call AGConnectUser.link to associate the mobile number with the current user. Generate the user UID associated with a mobile number to TextView and compare it with the UID generated for anonymous account sign-in to check whether the UIDs are the same.
    AGConnectAuth.getInstance().getCurrentUser().link(credential).addOnSuccessListener(new OnSuccessListener<SignInResult>() { @Override public void onSuccess(SignInResult signInResult) { String phoneNumber = signInResult.getUser().getPhone(); String uid = signInResult.getUser().getUid(); result.setText("phone number: " + phoneNumber + ", uid: " + uid); result.setVisibility(View.VISIBLE); Log.i(TAG, "phone number: " + phoneNumber + ", uid: " + uid); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { result.setText("Login error, please try again, error:" + e.getMessage()); result.setVisibility(View.VISIBLE); Log.e(TAG, "Login error, please try again, error:" + e.getMessage()); } });
  1. Run the Android Studio project to generate an APK and install the APK on the test mobile phone.
  2. Click ANONYMOUS LOGIN to sign in to the system and check whether the UID of the anonymous account is displayed.
  3. Enter the country code and mobile number, and click OBTAIN VER_CODE to check whether the mobile number can receive the verification code sent by the Auth Service server.
  4. Enter the verification code, click LINK PHONE, and check whether the UID of the mobile number is displayed on the page.
  5. Check whether the UID generated after anonymous sign-in is the same as that generated after a mobile number is bound.

Well done. You have successfully built an app that integrates Auth Service of AppGallery Connect and learned how to:

For details about APIs related to Auth Service of AppGallery Connect, please refer to API Reference.

To download the sample code, please click the button below:


Code copied