目录

HUAWEI ID Sign-In via Authorization Code (OAuth 2.0)

Scenario Description

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:

  1. Your app calls the sign-in API of the Account SDK to obtain the authorization code (valid for 5 minutes and can be used only once).
  2. Your app sends the authorization code to your app server through the API you specify. Then, your app server uses the authorization code to obtain the access token and refresh token by calling the API for Obtaining an Access Token of the Account Kit server (also an OAuth server).
  3. Your app server calls the API for Obtaining User Information of the Account Kit server and passes the access token to obtain user information.

Supported Devices

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 Your Start

  1. Make sure that you have made all necessary preparations.
  2. Make sure that your app has its own server.

Signing In with a HUAWEI ID

[h2]Sign-In Process

[h2]Client-Side Development

  1. Initialize the Account SDK.

    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();
                    }
                }
            });
        }
    }
  2. Add the sign-in button btn_hwid_sign_in.
    In your app's layout file, add the HUAWEI ID sign-in button as needed.

    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.

  3. Bind huaweiIdSignIn to the onClick callback method triggered after a tap on ResourceTable.Id_btn_hwid_sign_in to implement the HUAWEI ID sign-in function. After a tap on the HUAWEI ID sign-in button, your app will show the sign-in screen.
    Java
        Button mBtnHuaweiIdSignIn = (Button) findComponentById(ResourceTable.Id_btn_hwid_sign_in);
        mBtnHuaweiIdSignIn.setClickedListener((Component c) -> {
                huaweiIdSignIn();
            });
  4. Call the sign-in API of Account Kit to obtain the authorization code.

    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();
                                }
                            }
                        });
                    }
                }
            });
        }

[h2]Server-Side Development

  1. Receive the authorization code from the Account Kit server.

    Implement this by yourself.

  2. Use the authorization code to obtain the access token and refresh token.

    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.

    1. To facilitate API calling, Huawei provides you with accountservertool.jar developed based on the Java language. This JAR package encapsulates server-side RESTful APIs for your reference or direct use. For example, you can call the AuthCodeUtil.getTokensByCode(String code,String appId,String appSecret,String redirectUri) method in the package and pass the authorization code to obtain the access token and refresh token. To learn more about this package, please refer to How to Use accountservertool.jar.
    2. An authorization code can be used only once and is valid only for five minutes. If the error indicating that an authorization code has expired or has been used occurs, your app needs to obtain a new authorization code.
    3. Set the input parameter redirect_url in the request by following the instructions in Setting a Redirection URL.
  1. Call the API for Obtaining User Information provided by the Account Kit server to obtain user information, including the user nickname, profile picture, and email address.

    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.

    1. If you develop your app using the Java language, you can update the access token by using the AuthCodeUtil.updateAccessToken(String refreshToken,String appId,String appSecret) method in accountservertool.jar. For details, please refer to How to Use accountservertool.jar.
    2. When the access token has expired, if your app does not use the refresh token to request a new access token from the Account Kit server, the authorization of the signed-in HUAWEI ID will become invalid. As a result, functions that rely on the expired access token will be unavailable.
    3. When the access token becomes invalid because of reasons other than validity expiration (such as password change, account sign-out, and device deletion), your app can obtain a new access token by calling the sign-out API and then the silent sign-in API.

    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.

Signing Out of a HUAWEI ID

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.

  1. Bind signOut to the onClick callback method triggered after a tap on the sign-out button to implement the sign-out function.
    Java
            Button mBtnHuaweiIdSignOut = (Button) findComponentById(ResourceTable.Id_btn_signout);
            mBtnHuaweiIdSignOut .setClickedListener((Component c) -> {
                signOut();
            });
  2. Call the signOut method of the AccountAuthService class to sign out of a HUAWEI ID.
    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();
                    }
                }
            });
        }

Canceling Authorization

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.

  1. To this end, bind the cancelAuthorization method to the onClick callback method triggered after a tap on the authorization cancellation button.
    Java 
            mBtnCancelAuthorization = (Button) findComponentById(ResourceTable.Id_btn_cancelauthorization);
            mBtnCancelAuthorization.setClickedListener((Component c) -> {
                cancelAuthorization();
            });
  2. Call the cancelAuthorization method of the AccountAuthService class to implement the HUAWEI ID authorization cancellation function.
    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();
                    }
                }
            });
        }