You may want your app, which runs on a HarmonyOS mobile device, to support HUAWEI ID sign-in via authorization code through the OAuth 2.0 protocol.
Then, your app will obtain the user's authorization code (temporary authorization credential) for identity verification, enabling secure sign-in. When a user signs in for the first time, your app will request authorization from the user. After the user's identity verification information expires, your app server will use the refresh token to request a new access token from the Account Kit server. No more authorization is required, so this method is more reliable and convenient. However, this mode is applicable only to apps that have their own servers.
Process for authorization code-based HUAWEI ID sign-in:
Device Type |
OS Version |
HMS Core (APK) Version |
|---|---|---|
Phone and tablet |
HarmonyOS 2.0 or later |
5.0.0.300 or later |
Telematics device |
HarmonyOS 2.0 or later |
6.2.0.300 or later |
Huawei Vision and smartwatch (wearable, not lite wearable) |
HarmonyOS 2.0 or later |
6.5.0.300 or later |
The SDK for HarmonyOS (Java) can be used only when your app has only one HarmonyOS Ability Package (HAP).
Before using the SDK, your app shall initialize it by calling AccountAuthManager.init(AbilityPackage abilityPackage).
It is advised to finish the SDK initialization during your app initialization, which is shown in the following example:
Java // Initialize the Account SDK during your app initialization. public class MyApplication extends AbilityPackage { @Override public void onInitialize() { super.onInitialize(); // Initialize the SDK in the onInitialize method of the HarmonyOS app by calling initHuaweiAccountSDK. initHuaweiAccountSDK(); } @Override public void onEnd() { super.onEnd(); } // Call AccountAuthManager.init() of the Account SDK for the initialization. private void initHuaweiAccountSDK() { Task<Void> task; try { // Call AccountAuthManager.init for the initialization. task = AccountAuthManager.init(this); } catch (ApiException apiException) { apiException.getStatusCode(); return; } task.addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void v) { // The initialization is successful. } }); task.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { // The SDK fails to be initialized. if (e instanceof ApiException) { ApiException apiException = (ApiException) e; // Find the failure cause from the status code. For details, please refer to Error Codes. apiException.getStatusCode(); } } }); } }
If you need to develop a button for tapping to sign in with a HUAWEI ID, please refer to HUAWEI ID Sign-In Button Usage Rules.
Java
Button mBtnHuaweiIdSignIn = (Button) findComponentById(ResourceTable.Id_btn_hwid_sign_in);
mBtnHuaweiIdSignIn.setClickedListener((Component c) -> {
huaweiIdSignIn();
});
In the huaweiIdSignIn method, build AccountAuthParams (user information to be obtained after user authorization) and AccountAuthService (HUAWEI ID sign-in authorization service).
When building AccountAuthParams, call the AccountAuthParamsHelper.setAuthorizationCode() method to use the authorization code mode for HUAWEI ID sign-in.
Call silentSignIn for silent sign-in.
If the silent sign-in is successful, your app will obtain AuthAccount in the success event listener and then call getAuthorizationCode() to obtain the authorization code.
If the silent sign-in fails, your app will call signIn (API for foreground sign-in) in the failure event listener to show the authorization or sign-in screen. If the sign-in is successful through the signIn API, your app will obtain AuthAccount in the success event listener and then call getAuthorizationCode() to obtain the authorization code.
Java private void huaweiIdSignIn() { AccountAuthService accountAuthService; // 1. Use AccountAuthParams to specify the user information to be obtained after user authorization, including the user ID (OpenID and UnionID), email address, and profile (nickname and picture). // 2. By default, DEFAULT_AUTH_REQUEST_PARAM specifies two items to be obtained, that is, the user ID and profile. // 3. If your app needs to obtain the user's email address, call setEmail(). // 4. To support authorization code-based HUAWEI ID sign-in, use setAuthorizationCode(). All user information that your app is authorized to access can be obtained through the relevant API provided by the Account Kit server. AccountAuthParams accountAuthParams = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM) .setAuthorizationCode() .createParams(); try { accountAuthService = AccountAuthManager.getService(accountAuthParams); } catch (ApiException e) { // The initialization of authorization and sign-in fails. Find the failure cause from the status code. For details, please refer to Error Codes. e.getStatusCode(); return; } // Call the API for silent sign-in. // The silent sign-in will be successful if the user has authorized your app and signed in. // Otherwise, the silent sign-in will fail. Explicitly call the API for foreground sign-in in the failure event listener. Task<AuthAccount> task = accountAuthService.silentSignIn(); // Add a listener for processing the successful silent sign-in. task.addOnSuccessListener(new OnSuccessListener<AuthAccount>() { @Override public void onSuccess(AuthAccount authAccount) { // After the silent sign-in is successful, update the UI using the basic account information in the result. } }); // Add a listener for processing the failed silent sign-in. task.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { if (e instanceof ApiException) { // The silent sign-in fails. Explicitly call the API for foreground sign-in. Task task = accountAuthService.signIn(); if (task == null) { return; } task.addOnSuccessListener(new OnSuccessListener<AuthAccount>() { @Override public void onSuccess(AuthAccount account) { // Obtain the authorization code from getAuthorizationCode(). account.getAuthorizationCode(); } }); task.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { if (e instanceof ApiException) { ApiException apiException = (ApiException) e; // The sign-in failed. Find the failure cause from the status code. For details, please refer to Error Codes. apiException.getStatusCode(); } } }); } } }); }
Implement this by yourself.
After obtaining the authorization code, call the server API to obtain the access token and refresh token from the Account Kit server. For details about the API and the error codes that may be returned, please refer to Obtaining an Access Token and Error Codes.
If you develop your app using the Java language, you can use the AuthCodeUtil.getUserInfos(String accessToken,String getNickName) method in accountservertool.jar. For details, please refer to How to Use accountservertool.jar.
Processing after an access token has expired:
An access token has a short validity period (60 minutes). When an access token has expired or is about to expire (NSP_STATUS error code returned, if you use such a token), request a new access token from the Account Kit server by sending the refresh token (validity period: 180 days) through the API for Obtaining an Access Token.
Processing after a refresh token has expired:
The validity period of a refresh token is 180 days. When a refresh token has expired (error code returned, if you use such a token), the app server needs to notify your app to call the sign-in API of the Account SDK again and request the user to re-authorize.
Your app provides an entry for users to sign out of their HUAWEI IDs and calls the signOut API to notify the Account SDK of the sign-out. Then the Account SDK will delete the relevant HUAWEI ID information.
Java
Button mBtnHuaweiIdSignOut = (Button) findComponentById(ResourceTable.Id_btn_signout);
mBtnHuaweiIdSignOut .setClickedListener((Component c) -> {
signOut();
});
Java private void signOut() { AccountAuthService accountAuthService = null; AccountAuthParams accountAuthParams = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setEmail().createParams(); try { accountAuthService = AccountAuthManager.getService(accountAuthParams); } catch (ApiException e) { // The initialization of authorization and sign-in fails. Find the failure cause from the status code. For details, please refer to Error Codes. e.getStatusCode(); return; } Task<Void> task = accountAuthService.signOut(); task.addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void v) { // The sign-out is successful. Add the processing logic after the sign-out. } }); task.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { // The sign-out fails. if (e instanceof ApiException) { ApiException apiException = (ApiException) e; // Find the failure cause from the status code. For details, please refer to Error Codes. apiException.getStatusCode(); } } }); }
To improve privacy security, your app should allow users to cancel authorization.
After a user request to cancel authorization from your app, the cancelAuthorization method of the AccountAuthService class is called to complete the cancellation.
Java
mBtnCancelAuthorization = (Button) findComponentById(ResourceTable.Id_btn_cancelauthorization);
mBtnCancelAuthorization.setClickedListener((Component c) -> {
cancelAuthorization();
});
Java private void cancelAuthorization() { AccountAuthService accountAuthService; AccountAuthParams accountAuthParams = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setEmail().createParams(); try { accountAuthService = AccountAuthManager.getService(accountAuthParams); } catch (ApiException e) { // The initialization of authorization and sign-in fails. Find the failure cause from the status code. For details, please refer to Error Codes. e.getStatusCode(); return; } // Call the authorization cancellation API. Task<Void> task = accountAuthService.cancelAuthorization(); task.addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void v) { // Authorization cancellation is successful. } }); task.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { // Authorization cancellation fails. if (e instanceof ApiException) { ApiException apiException = (ApiException) e; // Find the failure cause from the status code. For details, please refer to Error Codes. apiException.getStatusCode(); } } }); }