Overview

There are over 500 million registered HUAWEI ID users across the globe. HUAWEI ID enables users to sign in to an app with just a tap. By binding your apps to HUAWEI ID, you can attract new users, by leveraging the enormous HUAWEI ID user base. HUAWEI ID complies with the OAuth 2.0 and OpenID Connect protocols.
To use HUAWEI ID, you will need to:

What You Will Create

In this codelab, you will use the demo project that has been created for you, to call HUAWEI ID APIs. Through the demo project, you will:

What You Will Learn

Hardware Requirements

Software Requirements

Creating an App and Obtaining the Configuration File

Create an app in AppGallery Connect and obtain the project configuration file agconnect-services.json. The procedure is as follows:

For details, see the HMS Core 3.0 Integration Preparation.

  1. In AppGallery Connect, go to Develop > Overview > Manage APIs.
  2. On the service management page, toggle the Huawei ID switch.

You have now successfully enabled HUAWEI ID service for the app that you have created.

Adding Configuration File

Move the downloaded agconnect-services.json file to the root directory of the app module in your Android Studio project.

Configuring signature.

Configuring the Maven Repository Address for HMS SDK.

  1. Open the build.gradle file in the root directory of your Android Studio project.
  2. Go to allprojects->repositories and buildscript->repositories, and configure the Maven repository address for HMS SDK.
    repositories { maven {url 'http://developer.huawei.com/repo/'} }
  3. Go to buildscript ->dependencies and add relevant configurations.
    buildscript { dependencies { classpath 'com.huawei.agconnect:agcp:1.0.0.300' } }
  4. Open the build.gradle file in the app directory.
  5. Add compile dependencies to "dependencies" and replace {version} with the current HMS SDK version number, which is 3.0.0.300.
    dependencies { implementation 'com.huawei.hms:hwid:{version}' }
  6. Add relevant configurations to the file header.
    apply plugin: 'com.huawei.agconnect'
  7. Click Sync Now to synchronize your project.

Configuring Obfuscation Scripts

  1. Open proguard-rules.pro, the obfuscation configuration file of your Android Studio project.
  2. Add obfuscation configurations.
    -ignorewarning -keepattributes *Annotation* -keepattributes Exceptions -keepattributes InnerClasses -keepattributes Signature -keepattributes SourceFile,LineNumberTable -keep class com.hianalytics.android.**{*;} -keep class com.huawei.updatesdk.**{*;} -keep class com.huawei.hms.**{*;}

Scenarios that involve interaction with HUAWEI ID APIs include: sign-in, silent sign-in, sign-out, and authorization cancellation. In this codelab, you can create the UI in your Android Studio project, by referring to the following UI layout.

Signing in with the ID Token Method

ID Token Process

  1. The user taps the HUAWEI ID sign-in icon and requests to sign in with a HUAWEI ID.
  2. HMS SDK displays the user sign-in and authorization page, explicitly notifying the user of the content to be authorized, based on the authorization scope carried in the sign-in request.
  3. After the user manually authorizes the app to access the content in question, HMS SDK returns the ID Token information to the app.
  4. The app verifies the ID Token locally or from the Huawei ID server.

ID Token Sample Code

1. Display the HUAWEI ID sign-in icon.

The app displays the HUAWEI ID sign-in icon on the sign-in page. For details about the icon specifications, please refer to Huawei Icon Specifications.

Call the requestIdToken method of HuaweiIdSignInOptions.Builder to request authorization.

HuaweiIdSignInOptions mSignInOptions; mSignInOptions = new HuaweiIdSignInOptions.Builder(HuaweiIdSignInOptions.DEFAULT_SIGN_IN).requestIdToken("").build();

Call the getClient method of HuaweiIdSignIn to initialize the HuaweiIdSignInClient object.

HuaweiIdSignInClient mSignInClient = HuaweiIdSignIn.getClient(HuaweiIdActivity.this, mSignInOptions);

Call the getSignInIntent method of HuaweiIdSignInClient and display the HUAWEI ID sign-in and authorization page.

startActivityForResult(mSignInClient.getSignInIntent(), Constant.REQUEST_SIGN_IN_LOGIN);

Process the sign-in result after successful authorization.

protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == Constant.REQUEST_SIGN_IN_LOGIN) { //login success //get user message by getSignedInAccountFromIntent Task<SignInHuaweiId> signInHuaweiIdTask = HuaweiIdSignIn.getSignedInAccountFromIntent(data); if (signInHuaweiIdTask.isSuccessful()) { SignInHuaweiId huaweiAccount = signInHuaweiIdTask.getResult(); Log.i(TAG, "signIn success " + huaweiAccount.getDisplayName()); } else { Log.i(TAG, "signIn failed: " + ((ApiException) signInHuaweiIdTask.getException()).getStatusCode()); } } }

Signing in with the Authorization Code Method

HUAWEI ID also supports user sign-in with an Authorization Code. Hoowever, it only applies to apps that run on independent developer servers.

Authorization Code Process

  1. The user taps the HUAWEI ID sign-in icon, and requests to sign in with a HUAWEI ID.
  2. HMS SDK displays the user sign-in and authorization page, explicitly notifying the user of the content to be authorized based on the authorization scope carried in the sign-in request.
  3. After the user manually authorizes the app to access the content in question, HMS SDK returns the Authorization Code information to the app.
  4. Based on the Authorization Code, the app obtains the Access Token, Refresh Token, and ID Token from the Huawei ID server.
  5. If the ID Token has expired, obtain the new Access Token or ID Token by using the Refresh Token.

Authorization Code Sample Code

1. Display the HUAWEI ID sign-in icon.

The app displays the HUAWEI ID sign-in icon on the sign-in page. For details about the icon specifications, please refer to Huawei Icon Specifications.

Call the requestServerAuthCode method of HuaweiIdSignInOptions.Builder to request authorization.

HuaweiIdSignInOptions signInOptions = new HuaweiIdSignInOptions.Builder(HuaweiIdSignInOptions.DEFAULT_SIGN_IN).requestServerAuthCode().build();

Call the getClient method of HuaweiIdSignIn to initialize the HuaweiIdSignInClient object.

HuaweiIdSignInClient client = HuaweiIdSignIn.getClient(MainActivity.this, signInOptions);

Call the getSignInIntent method of HuaweiIdSignInClient and display the HUAWEI ID sign-in and authorization page.

startActivityForResult(mSignInClient.getSignInIntent(), Constant.REQUEST_SIGN_IN_LOGIN_CODE);

Process the sign-in result after successful authorization.

protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == Constant.REQUEST_SIGN_IN_LOGIN_CODE) { //login success Task<SignInHuaweiId> signInHuaweiIdTask = HuaweiIdSignIn.getSignedInAccountFromIntent(data); if (signInHuaweiIdTask.isSuccessful()) { SignInHuaweiId huaweiAccount = signInHuaweiIdTask.getResult(); Log.i(TAG, "signIn get code success."); } else { Log.i(TAG, "signIn get code failed: " + ((ApiException) signInHuaweiIdTask.getException()).getStatusCode()); } } }

The app client reports the obtained Authorization Code to the app server, which will call the API at /oauth2/v3/token to request the ID Token, Access Token, and Refresh Token from the Huawei ID server.

Request example:

POST /oauth2/v3/token HTTP/1.1 Host: oauth-login.cloud.huawei.com Content-Type: application/x-www-form-urlencoded grant_type=authorization_code& code=ANXxSNjwQDugOnqeikRMu2bKaXCdlLxn& client_id=12345& code_verifier=123444444dfd4sadfsdwew321454567587658776t896fdfgdscvvbfxdgfdgfdsfasdfsdgd233& redirect_uri=hms%3A%2F%2Fredirect_uri& need_open_uid=true

Response example:

HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Cache-Control: no-store Pragma: no-cache { "access_token": "CFyJ21sNODl16eV9y2vu3CwQk9DBr32BkOcxxgAd7MZUR5th1giyTk5\/kA+QDAyxou+\/5U2zzBRcf3qgLkkFdtbbC+mM3zFV7xj7CCEMHc5Tw92al0Y=", "refresh_token": "CF13G0sRaGybtYt7SIyeUILNORtTFwMgz4ao5C7j7vtgLPt6ogmXKjdI8RS\/YlyS71z4DyP6kEMnOrRlmNK0KhdOUNWd+qVLLRsEEHkqRIKpuAkPvL8=", "expires_in": 3600, "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjExOGRmMjU0YjgzNzE4OWQxYmMyYmU5NjUwYTgyMTEyYzAwZGY1YTQiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJhenAiOiI3ODI0NTY2Njc4OTgtc2M0MzE3Y2l0NGEwMjB0NzdrbGdsbWo1ZjA4YWtnMWIuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiI3ODI0NTY2Njc4OTgtN2NkNGJpYWRkaGVwNGc4cnZic2VlOGtwcDA5Zm1hNzIuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMDE3MTIxMzkwMzgwNDE2MDc0MTQiLCJlbWFpbCI6Inh1ZXpoZW5odWF0anVAc2luYS5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwicGljdHVyZSI6Imh0dHBzOi8vbGg1Lmdvb2dsZXVzZXJjb250ZW50LmNvbS8tMm9lTTllT09zNTAvQUFBQUFBQUFBQUkvQUFBQUFBQUFBQkkvMVpOSC0xdmxxc3cvczk2LWMvcGhvdG8uanBnIiwiaWF0IjoxNTYxNDUxMTUyLCJleHAiOjE1NjE0NTQ3NTJ9.Eo9IHMkid596jvt1YYzNsRtDq9c9K9dbougkU41Noh7TXNiko86_RuWwHID6k1kDg398AwC3wwH-t2hLcUjgrXPNd9XYU96Jp4-UxdDszP6ywEJgvvBCyTHzsi2auvKt_MnfSrs3qOKfh7noJvXq8AY-Hi3vqSUks5kGqbZKVzCHhBDO3RD9Fs9YHsB6w0XVKZojPOBDaAT_TiijoChn-Q-e8NbSGUx52OgeH-Nw5lOj6JVb_7fb6ucWRzlhiQuzFjklevLVw2pjw1MxKbl1vfRp0X699uZBVjgl9hj1L7LSDObuPzLiXF7ojji5JKYC6zIwAtZQUZ_VUmSk01GDLQ", "scope": "openid profile email", "token_type": "Bearer", "open_id": "MDFAMzAwMDUxODgzQDNiaODc3NTkzNGRlNmNiaMzBlNmQ2YjAzNTgzNTJhMDNjQDkwMGQwYTY1NmE1NmNlNTU1M2EzMWY3Y2VmZWQwOGJlYTRkZTU4ZjM5YWFmOWNhNTk0ODEyZA", }

The Access Token has a short validity period (currently, 60 minutes). When the Access Token obtained has expired or is about to expire, request the new Access Token from the Huawei ID server by sending the Refresh Token through the API at /oauth2/v3/token.

Request example:

POST /oauth2/v3/token HTTP/1.1 Host: oauth-login.cloud.huawei.com Content-Type: application/x-www-form-urlencoded grant_type=refresh_token& client_id=12345& client_secret=bKaZ0VE3EYrXaXCdCe3d2k9few& refresh_toekn=CF2Mm03n0aos9iZZ8nIhfyDtoXy74CXeBi50gVVhMpB0IUzlv9ZwizEvTBhVoF820ZPim0JwNR9j2p1qgEQWnIVYZRlp4T6ezMgekUnsHBkvNev5rd2MdfQMLP

Response example:

HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Cache-Control: no-store Pragma: no-cache { "access_token": "CFyJ4J\/l6wuwcFqYOJG4maq2ca8RAV+g0i+mel6qCV5lvqH0PYtW0+BNwfHWg0AqM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Sk01GDLQ", "expires_in": 3600, "scope": "openid profile email", "token_type": "Bearer" }

After completing the development process, click button, run your Android Studio project and generate the APK. Then, install the APK on your mobile phone for testing. The test results are as shown below:

Well done. You have successfully completed this codelab, and learned:

HUAWEI ID Service Introduction and APIs

Download the source code for the demo that is used in this codelab

Download

Code copied