There are up to one billion HUAWEI ID users across the globe. Apps with HUAWEI Account Kit integrated allow users to sign in using their HUAWEI IDs with just a tap. By integrating Account Kit, you can attract new users, by leveraging the enormous HUAWEI ID user base. Account Kit complies with the OAuth 2.0 and OpenID Connect protocols.
To use this Kit, you will need to:
In this codelab, we provide a demo project for you to call the APIs of Account Kit. Through the demo project, you'll be able to implement the following functions:
In this codelab, you will learn how to:
Android app development basics
Before you get started, you must register as a Huawei developer and complete identity verification on HUAWEI Developers. For details, please refer to Registration and Verification.
To integrate Account Kit, you must complete the following preparations:
Now, you have successfully enabled Account Kit for your app.
dependencies {
implementation 'com.huawei.hms:hwid:{version}'
}
Click Sync Now to synchronize the project.
The procedure for configuring the Maven repository address in Android Studio is different for Gradle plugin earlier than 7.0, Gradle plugin 7.0, and Gradle plugin 7.1 or later. Click a relevant link below to find the configuration procedure for the specific Gradle plugin version.
Gradle plugin earlier than 7.0 | Gradle plugin 7.0 | Gradle plugin 7.1 or later |
Gradle plugin earlier than 7.0
a. Open the build.gradle file in the root directory of your Android Studio project.
b. Add the AppGallery Connect plugin and the Maven repository.
buildscript {
repositories {
google()
jcenter()
// Configure the Maven repository address for the HMS Core SDK.
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
...
// Add the AppGallery Connect plugin configuration. You are advised to use the latest plugin version.
classpath 'com.huawei.agconnect:agcp:1.6.0.300'
}
}
allprojects {
repositories {
google()
jcenter()
// Configure the Maven repository address for the HMS Core SDK.
maven {url 'https://developer.huawei.com/repo/'}
}
}
Gradle plugin 7.0
a. Open the build.gradle file in the root directory of your Android Studio project.
b. Add the AppGallery Connect plugin and the Maven repository.
buildscript {
repositories {
google()
jcenter()
// Configure the Maven repository address for the HMS Core SDK.
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
...
// Add the AppGallery Connect plugin configuration. You are advised to use the latest plugin version.
classpath 'com.huawei.agconnect:agcp:1.6.0.300'
}
}
c. Open the project-level settings.gradle file and configure the Maven repository address for the HMS Core SDK.
dependencyResolutionManagement {
...
repositories {
google()
jcenter()
// Configure the Maven repository address for the HMS Core SDK.
maven {url 'https://developer.huawei.com/repo/'}
}
}
Gradle plugin 7.1 or later
a. Open the build.gradle file in the root directory of your Android Studio project.
b. If the agconnect-services.json file has been added to the app, go to buildscript > dependencies and add the AppGallery Connect plugin configuration.
buildscript {
dependencies {
...
// Add the AppGallery Connect plugin configuration. You are advised to use the latest plugin version.
classpath 'com.huawei.agconnect:agcp:1.6.0.300'
}
}
c. Open the project-level settings.gradle file and configure the Maven repository address for the HMS Core SDK.
pluginManagement {
repositories {
gradlePluginPortal()
google()
mavenCentral()
// Configure the Maven repository address for the HMS Core SDK.
maven { url 'https://developer.huawei.com/repo/' }
}
}
dependencyResolutionManagement {
...
repositories {
google()
mavenCentral()
// Configure the Maven repository address for the HMS Core SDK.
maven { url 'https://developer.huawei.com/repo/' }
}
}
Open the obfuscation configuration file proguard-rules.pro in the app directory of your project.
Add configurations to exclude the HMS Core SDK from obfuscation.
-ignorewarnings
-keepattributes *Annotation*
-keepattributes Exceptions
-keepattributes InnerClasses
-keepattributes Signature
-keepattributes SourceFile,LineNumberTable
-keep class com.huawei.hianalytics.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}
"R.string.hms*",
"R.string.connect_server_fail_prompt_toast",
"R.string.getting_message_fail_prompt_toast",
"R.string.no_available_network_prompt_toast",
"R.string.third_app_*",
"R.string.upsdk_*",
"R.layout.hms*",
"R.layout.upsdk_*",
"R.drawable.upsdk*",
"R.color.upsdk*",
"R.dimen.upsdk*",
"R.style.upsdk*",
"R.string.agc*"
The Account SDK requires permissions to obtain the network status and Wi-Fi status. Declare the permissions in the AndroidManifest.xml file:
<!--check network permissions-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--check wifi state-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Account Kit provides APIs for normal sign-in, silent sign-in, sign-out, and authorization revoking. In this codelab, you can create a UI in your Android Studio project. An example is shown in the following figure.
Call thesetIdTokenn method ofAccountAuthParamsHelperr to request authorization.
Java
AccountAuthParams authParams = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setIdToken().createParams();
Kotlin
val authParams : AccountAuthParams = AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setIdToken().createParams()
AccountAuthService service = AccountAuthManager.getService(MainActivity.this, authParams);
Kotlin
val service : AccountAuthService = AccountAuthManager.getService(this@MainActivity, authParams)
startActivityForResult(service.getSignInIntent(), 8888);
Kotlin
startActivityForResult(service.signInIntent, 8888)
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
// Process the authorization result and obtain an ID token from AuthAccount.
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 8888) {
Task<AuthAccount> authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data);
if (authAccountTask.isSuccessful()) {
// The sign-in is successful, and the user's ID information and ID token are obtained.
AuthAccount authAccount = authAccountTask.getResult();
Log.i(TAG, "idToken:" + authAccount.getIdToken());
} else {
// The sign-in failed. No processing is required. Logs are recorded for fault locating.
Log.e(TAG, "sign in failed : " +((ApiException) authAccountTask.getException()).getStatusCode());
}
}
}
Kotlin
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
// Process the authorization result and obtain an ID to**AuthAccount**thAccount.
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 8888) {
val authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data)
if (authAccountTask.isSuccessful) {
// The sign-in is successful, and the user's ID information and ID token are obtained.
val authAccount = authAccountTask.result
Log.i(TAG, "idToken:" + authAccount.idToken)
} else {
// The sign-in failed. No processing is required. Logs are recorded for fault locating.
Log.e(TAG, "sign in failed : " + (authAccountTask.exception as ApiException).statusCode)
}
}
}
Account Kit also allows for sign-in using an ID in authorization code mode. Use this mode when you have your own app server.
Call the setAuthorizationCode method of AccountAuthParamsHelper to request authorization.
Java
AccountAuthParams authParams = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setAuthorizationCode().createParams();
Kotlin
val authParams : AccountAuthParams = AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setAuthorizationCode().createParams()
AccountAuthService service = AccountAuthManager.getService(MainActivity.this, authParams);
Kotlin
val service : AccountAuthService = AccountAuthManager.getService(this@MainActivity, authParams)
startActivityForResult(service.getSignInIntent(), 8888);
Kotlin
startActivityForResult(service.signInIntent, 8888)
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
// Process the authorization result and obtain an authorization code from AuthAccount.
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 8888) {
Task<AuthAccount> authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data);
if (authAccountTask.isSuccessful()) {
// The sign-in is successful, and the user's ID information and authorization code are obtained.
AuthAccount authAccount = authAccountTask.getResult();
Log.i(TAG, "serverAuthCode:" + authAccount.getAuthorizationCode());
} else {
// The sign-in failed.
Log.e(TAG, "sign in failed:" + ((ApiException) authAccountTask.getException()).getStatusCode());
}
}
}
Kotlin
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
// Process the authorization result and obtain an authorization c**AuthAccount**thAccount.
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 8888) {
val authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data)
if (authAccountTask.isSuccessful) {
// The sign-in is successful, and the user's ID information and authorization code are obtained.
val authAccount = authAccountTask.result
Log.i(TAG, "serverAuthCode:" + authAccount.authorizationCode)
} else {
// The sign-in failed.
Log.e(TAG, "sign in failed:" + (authAccountTask.exception as ApiException).statusCode)
}
}
}
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_token=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+BNwfHWg0AqMnW6ZdBvUgs7ijkxMFh1xVP\/B+vQXz3PWsivkKCuL78XtbLt7vs=",
"id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjExOGRmMjU0YjgzNzE4OWQxYmMyYmU5NjUwYTgyMTEyYzAwZGY1YTQiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJhenAiOiI3ODI0NTY2Njc4OTgtc2M0MzE3Y2l0NGEwMjB0NzdrbGdsbWo1ZjA4YWtnMWIuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiI3ODI0NTY2Njc4OTgtN2NkNGJpYWRkaGVwNGc4cnZic2VlOGtwcDA5Zm1hNzIuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMDE3MTIxMzkwMzgwNDE2MDc0MTQiLCJlbWFpbCI6Inh1ZXpoZW5odWF0anVAc2luYS5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwicGljdHVyZSI6Imh0dHBzOi8vbGg1Lmdvb2dsZXVzZXJjb250ZW50LmNvbS8tMm9lTTllT09zNTAvQUFBQUFBQUFBQUkvQUFBQUFBQUFBQkkvMVpOSC0xdmxxc3cvczk2LWMvcGhvdG8uanBnIiwiaWF0IjoxNTYxNDUxMTUyLCJleHAiOjE1NjE0NTQ3NTJ9.Eo9IHMkid596jvt1YYzNsRtDq9c9K9dbougkU41Noh7TXNiko86_RuWwHID6k1kDg398AwC3wwH-t2hLcUjgrXPNd9XYU96Jp4-UxdDszP6ywEJgvvBCyTHzsi2auvKt_MnfSrs3qOKfh7noJvXq8AY-Hi3vqSUks5kGqbZKVzCHhBDO3RD9Fs9YHsB6w0XVKZojPOBDaAT_TiijoChn-Q-e8NbSGUx52OgeH-Nw5lOj6JVb_7fb6ucWRzlhiQuzFjklevLVw2pjw1MxKbl1vfRp0X699uZBVjgl9hj1L7LSDObuPzLiXF7ojji5JKYC6zIwAtZQUZ_VUmSk01GDLQ",
"expires_in": 3600,
"scope": "openid profile email",
"token_type": "Bearer"
}
AccountAuthParams authParams = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).createParams();
Kotlin
val authParams : AccountAuthParams = AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).createParams()
AccountAuthService service = AccountAuthManager.getService(MainActivity.this, authParams);
Kotlin
val service : AccountAuthService = AccountAuthManager.getService(this@MainActivity, authParams)
Task<AuthAccount> task = service.silentSignIn();
Kotlin
val task : Task<AuthAccount> = service.silentSignIn()
task.addOnSuccessListener(new OnSuccessListener<AuthAccount>() {
@Override
public void onSuccess(AuthAccount authAccount) {
// Obtain the user's ID information.
Log.i(TAG, "displayName:" + authAccount.getDisplayName());
// Obtain the ID type (0: HUAWEI ID; 1: AppTouch ID).
Log.i(TAG, "accountFlag:" + authAccount.getAccountFlag());
}
});
Kotlin
task.addOnSuccessListener { authAccount ->
// Obtain the user's ID information.
Log.i(TAG, "displayName:" + authAccount.displayName)
// Obtain the **0**D type (0: HU**1**WEI ID; 1: AppTouch ID).
Log.i(TAG, "accountFlag:" + authAccount.accountFlag);
}
If the authorization fails, the user may have not successfully signed in before. Your app may determine whether to call the getSignInIntent method of AccountAuthService to explicitly display the authorization screen.
Java
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// The sign-in failed. Your app can **getSignInIntent()**nIntent() method to explicitly display the authorization screen.
if (e instanceof ApiException) {
ApiException apiException = (ApiException) e;
Log.i(TAG, "sign failed status:" + apiException.getStatusCode());
}
}
});
Kotlin
task.addOnFailureListener { e ->
// The sign-in failed. Your app can **getSignInIntent()**nIntent() method to explicitly display the authorization screen.
if (e is ApiException) {
Log.i(TAG, "sign failed status:" + e.statusCode)
}
}
// service indicates the AccountAuthService instance generated using the getService method during the sign-in authorization.
Task<Void> signOutTask = service.signOut();
Kotlin
// service indicates the AccountAuthService instance generated using the getService method during the sign-in authorization.
val signOutTask = service.signOut()
signOutTask.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
// Processing after the sign-out.
Log.i(TAG, "signOut complete");
}
});
Kotlin
signOutTask.addOnCompleteListener { it ->
// Processing after the sign-out.
Log.i(TAG, "signOut complete")
}
// service indicates the AccountAuthService instance generated using the getService method during the sign-in authorization.
service.cancelAuthorization().addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(Task task) {
if (task.isSuccessful()) {
// Processing after a successful authorization revoking.
Log.i(TAG, "onSuccess: ");
} else {
// Handle the exception.
Exception exception = task.getException();
if (exception instanceof ApiException){
int statusCode = ((ApiException) exception).getStatusCode();
Log.i(TAG, "onFailure: " + statusCode);
}
}
}
});
Kotlin
// service indicates the AccountAuthService instance generated using the getService method during the sign-in authorization.
service.cancelAuthorization().addOnCompleteListener { task ->
if (task.isSuccessful) {
// Processing after a successful authorization revoking.
Log.i(TAG, "onSuccess: ")
} else {
// Handle the exception.
val exception = task.exception
if (exception is ApiException) {
val statusCode = exception.statusCode
Log.i(TAG, "onFailure: $statusCode")
}
}
}
Click to run your project to generate an APK and install it on the test phone. After launching the demo app, you'll see the following screen:
Well done. You have successfully completed this codelab and learned how to:
For more information, please click the following link:
API Reference
To download the sample code, please click the button below: