目录

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

Scenario Description

You may want your app, which runs on an Android phone, tablet, or smart display, 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.

    If your app needs to be released on AppTouch, follow the instructions in Scenario Description.

Before Your Start

  1. Make sure that you have made all necessary preparations.
  2. Make sure that your app has its own server.
  3. You can download the demo to try it out.

Signing In with a HUAWEI ID

[h2]Sign-In Process

[h2]Client-Side Development

  1. Implement the HUAWEI ID sign-in button.

    HuaweiIdAuthButton is a button control provided by Account Kit for you to quickly design a HUAWEI ID sign-in button that complies with HUAWEI ID Sign-In Button Usage Rules.

    In the XML file under res > layout, declare the button control. Then you can set relevant parameters to tailor the style of the HUAWEI ID sign-in button to your app by following the instructions in HuaweiIdAuthButton Usage Guide.

    <!-- Define an ID for the button control. -->
    <com.huawei.hms.support.hwid.ui.HuaweiIdAuthButton
        android:id="@+id/HuaweiIdAuthButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    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.

  2. Show the authorization screen to request authorization from the user.

    Bind silentSignInByHwId to the onClick callback method triggered after a tap on R.id.HuaweiIdAuthButton 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
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
            // activity_main is the name of the custom layout file.
        setContentView(R.layout.activity_main);
        findViewById(R.id.HuaweiIdAuthButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                silentSignInByHwId();
            }
        });
    }
    Kotlin
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
            // activity_main is the name of the custom layout file.
        setContentView(R.layout.activity_main)
        findViewById<View>(R.id.HuaweiIdAuthButton).setOnClickListener { silentSignInByHwId() }
    }

    In the silentSignInByHwId method, build AccountAuthParams (user information to be obtained after user authorization) and AccountAuthService (HUAWEI ID sign-in authorization service). Then call the silentSignIn API for silent sign-in. If the silent sign-in is successful, your app will directly obtain the authorization code. If the silent sign-in fails, your app will call the getSignInIntent API to show the authorization or sign-in screen.

    Java
        // AccountAuthService provides a set of APIs, including silentSignIn, getSignInIntent, and signOut.
    private AccountAuthService mAuthService;
     
        // Specify the user information to be obtained after user authorization.
    private AccountAuthParams mAuthParam;
     
        // Define the request code for signInIntent.
    private static final int REQUEST_CODE_SIGN_IN = 1000;
     
        // Define the log tag.
    private static final String TAG = "Account";
     
    /**
     * Silent sign-in: If a user has authorized your app and signed in, no authorization or sign-in screen will appear during subsequent sign-ins, and the user will directly sign in.
     * After a successful silent sign-in, the HUAWEI ID information will be returned in the success event listener.
         * If the user has not authorized your app or signed in, the silent sign-in will fail. In this case, your app will show the authorization or sign-in screen to the user.
     */
    private void silentSignInByHwId() {
            //  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.
        mAuthParam = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
                    .setEmail()
                    .setAuthorizationCode()
                    .createParams();
     
            // Use AccountAuthParams to build AccountAuthService.
        mAuthService = AccountAuthManager.getService(this, mAuthParam);
     
            // Sign in with a HUAWEI ID silently.
        Task<AuthAccount> task = mAuthService.silentSignIn();
        task.addOnSuccessListener(new OnSuccessListener<AuthAccount>() {
            @Override
            public void onSuccess(AuthAccount authAccount) {
                    // The silent sign-in is successful. Process the returned AuthAccount object to obtain the HUAWEI ID information.
                dealWithResultOfSignIn(authAccount);
            }
        });
        task.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                    // The silent sign-in fails. Your app will call getSignInIntent() to show the authorization or sign-in screen.
                if (e instanceof ApiException) {
                    ApiException apiException = (ApiException) e;
                    Intent signInIntent = mAuthService.getSignInIntent();
                    // If your app appears in full screen mode when a user tries to sign in, that is, with no status bar at the top of the device screen, add the following parameter in the intent:
                    // intent.putExtra(CommonConstant.RequestParams.IS_FULL_SCREEN, true);
                    // Check the details in this FAQ.
                    signInIntent.putExtra(CommonConstant.RequestParams.IS_FULL_SCREEN, true);
                    startActivityForResult(signInIntent, REQUEST_CODE_SIGN_IN);
                }
            }
        });
    }
     
    /**
         * Process the returned AuthAccount object to obtain the HUAWEI ID information.
     *
         * @param authAccount AuthAccount object, which contains the HUAWEI ID information.
     */
    private void dealWithResultOfSignIn(AuthAccount authAccount) {
        Log.i(TAG,"code:"+authAccount.getAuthorizationCode());
            // TODO: After obtaining the authorization code, your app needs to send it to the app server.
     
    }
    Kotlin
        // AccountAuthService provides a set of APIs, including silentSignIn, getSignInIntent, and signOut.
    private var mAuthService: AccountAuthService? = null
    
        // Specify the user information to be obtained after user authorization.
    private var mAuthParam: AccountAuthParams? = null
    
        // Define the request code for signInIntent.
    private val REQUEST_CODE_SIGN_IN = 1000
    
        // Define the log tag.
    private val TAG = "Account"
    
    /**
         * Silent sign-in: If a user has authorized your app and signed in, no authorization or sign-in screen will appear during subsequent sign-ins, and the user will directly sign in.
         * After a successful silent sign-in, the HUAWEI ID information will be returned in the success event listener.
         * If the user has not authorized your app or signed in, the silent sign-in will fail. In this case, your app will show the authorization or sign-in screen to the user.
     */
    private fun silentSignInByHwId() {
            //  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.
        mAuthParam = AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
                    .setEmail()
                    .setAuthorizationCode()
                    .createParams()
    
            // Use AccountAuthParams to build AccountAuthService.
        mAuthService = AccountAuthManager.getService(this, mAuthParam)
    
            // Sign in with a HUAWEI ID silently.
        val task = mAuthService!!.silentSignIn()
            task.addOnSuccessListener { authAccount -> // The silent sign-in is successful. Process the returned AuthAccount object to obtain the HUAWEI ID information.
            dealWithResultOfSignIn(authAccount)
        }
            task.addOnFailureListener { e -> // The silent sign-in fails. Your app will call getSignInIntent() to show the authorization or sign-in screen.
            if (e is ApiException) {
                val apiException = e
                val signInIntent = mAuthService!!.getSignInIntent()
                // If your app appears in full screen mode when a user tries to sign in, that is, with no status bar at the top of the device screen, add the following parameter in the intent:
                // intent.putExtra(CommonConstant.RequestParams.IS_FULL_SCREEN, true)
                // Check the details in this FAQ.
                signInIntent.putExtra(CommonConstant.RequestParams.IS_FULL_SCREEN, true)
                startActivityForResult(signInIntent, REQUEST_CODE_SIGN_IN)
            }
        }
    }
    
    /**
         * Process the returned AuthAccount object to obtain the HUAWEI ID information.
     *
         * @param authAccount AuthAccount object, which contains the HUAWEI ID information.
     */
    private fun dealWithResultOfSignIn(authAccount: AuthAccount) {
        Log.i(TAG, "code:" + authAccount.authorizationCode)
            // TODO: After obtaining the authorization code, your app needs to send it to the app server.
    
    }
  3. After a successful sign-in through the getSignInIntent API, process the sign-in result to obtain the authorization code, and then send it to the app server.
    Java
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SIGN_IN) {
            Log.i(TAG, "onActivitResult of sigInInIntent, request code: " + REQUEST_CODE_SIGN_IN);
            Task<AuthAccount> authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data);
            if (authAccountTask.isSuccessful()) {
                    // The sign-in is successful, and the authAccount object that contains the HUAWEI ID information is obtained.
                AuthAccount authAccount = authAccountTask.getResult();
                dealWithResultOfSignIn(authAccount);
                Log.i(TAG, "onActivitResult of sigInInIntent, request code: " + REQUEST_CODE_SIGN_IN);
            } else {
                // The sign-in fails. Find the failure cause from the status code. For more information, please refer to Error Codes.
                Log.e(TAG, "sign in failed : " +((ApiException)authAccountTask.getException()).getStatusCode());
            }
        }
    }
    Kotlin
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_SIGN_IN) {
            Log.i(TAG, "onActivitResult of sigInInIntent, request code: $REQUEST_CODE_SIGN_IN")
            val authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data)
            if (authAccountTask.isSuccessful) {
                    // The sign-in is successful, and the authAccount object that contains the HUAWEI ID information is obtained.
                val authAccount = authAccountTask.result
                dealWithResultOfSignIn(authAccount)
                Log.i(TAG, "onActivitResult of sigInInIntent, request code: $REQUEST_CODE_SIGN_IN")
            } else {
                // The sign-in fails. Find the failure cause from the status code. For more information, please refer to Error Codes.
                Log.e(TAG, "sign in failed : " + (authAccountTask.exception as ApiException).statusCode)
            }
        }
    }

[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, your app uses it to obtain the access token and refresh token from the Account Kit server through the API for Obtaining an Access Token provided by this server. If any error occurs during the API call, please refer to 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 5 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.

(Optional) Independent Authorization

You can choose whether to implement this function as needed. If needed, follow the instructions in (Optional) Independent Authorization.

Signing Out of a HUAWEI ID

When a user requests to sign out, your app will call the signOut API to sign the user out and notify the Account SDK of the sign-out. Then the Account SDK will delete the relevant HUAWEI ID information.

  1. Bind the signOut method to the onClick callback method triggered after a tap on HuaweiIdSignOutButton to implement the HUAWEI ID sign-out function.
    Java
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        findViewById(R.id.HuaweiIdSignOutButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signOut();
            }
        });
    }
    
    Kotlin
    override fun onCreate(savedInstanceState: Bundle?) {
        findViewById<View>(R.id.HuaweiIdSignOutButton).setOnClickListener { signOut() }
    }
  1. Call the signOut method of the AccountAuthService class to sign out of a HUAWEI ID.
    Java
    private void signOut() {
        Task<Void> signOutTask = mAuthService.signOut();
        signOutTask.addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.i(TAG, "signOut Success");
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                Log.i(TAG, "signOut fail");
            }
        });
    }
    
    Kotlin
    private fun signOut() {
        val signOutTask = mAuthService!!.signOut()
        signOutTask.addOnSuccessListener {
            Log.i(TAG, "signOut Success")
        }.addOnFailureListener {
            Log.i(TAG, "signOut fail")
        }
    }

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. Bind the cancelAuthorization method to the onClick callback method triggered after a tap on HuaweiIdCancelAuthButton to implement the HUAWEI ID authorization cancellation function.
    Java
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        findViewById(R.id.HuaweiIdCancelAuthButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancelAuthorization();
            }
        });
    }
    
    Kotlin
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        findViewById<View>(R.id.HuaweiIdCancelAuthButton).setOnClickListener { cancelAuthorization() }
    }
  1. Call the cancelAuthorization method of the AccountAuthService class to cancel HUAWEI ID authorization.
    Java
    private void cancelAuthorization() {
        Task<Void> task = mAuthService.cancelAuthorization();
        task.addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.i(TAG, "cancelAuthorization success");
            }
        });
        task.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                Log.i(TAG, "cancelAuthorization failure:" + e.getClass().getSimpleName());
            }
        });
    }
    
    Kotlin
    private fun cancelAuthorization() {
        val task = mAuthService!!.cancelAuthorization()
        task.addOnSuccessListener {
            Log.i(TAG, "cancelAuthorization success")
        }
        task.addOnFailureListener { e ->
            Log.i(TAG, "cancelAuthorization failure:" + e.javaClass.simpleName)
        }
    }