目录

@hms.core.authentication (Unified Authentication Service)

Module Overview

The @hms.core.authentication module provides unified authentication capabilities for apps integrating Account Kit. The core functions include signing in with a HUAWEI ID and obtaining user information associated with a HUAWEI ID.

In addition, this module provides two auxiliary capabilities: obtaining HUAWEI ID sign-in status and obtaining mobile number consistency status. These capabilities help optimize sign-in status management and improve the risk control logic for app security.

You can use HuaweiIDProvider and AuthenticationController together to implement the core functions of unified authentication provided by Account Kit.

HuaweiIDProvider: authentication factory class of Account Kit, which mainly creates request objects for HUAWEI ID sign-in, authorization, and authorization revocation. You can flexibly configure object properties based on specific service scenarios.

AuthenticationController: controller class of Account Kit, which receives and executes requests for HUAWEI ID sign-in, authorization, and authorization revocation. You need to pass the request object created by HuaweiIDProvider as an input parameter to the AuthenticationController.executeRequest method to send the request to the Account Kit server.

[h2]Basic Concepts

[h2]Sign-in with a HUAWEI ID

The @hms.core.authentication module provides secure and convenient HUAWEI ID sign-in capabilities.

You can use these sign-in capabilities to obtain an authorization code. The app server uses the authorization code to call the API for obtaining a user-level credential to request an access token from the Account Kit server, and then uses the access token to call the API for parsing a credential to obtain the user's UnionID/OpenID. The app server then checks whether the user has been associated with its existing user system based on the UnionID/OpenID. If so, user sign-in is complete; if not, the server creates a new user account, binds the UnionID/OpenID to it, and completes sign-in.

You need to use HuaweiIDProvider to construct a request object for HUAWEI ID sign-in and use AuthenticationController to execute the sign-in request. The pseudo-code of this process is as follows:

provider = new authentication.HuaweiIDProvider();
loginWithHuaweiIDRequest = provider.createLoginWithHuaweiIDRequest();
controller = new authentication.AuthenticationController(context);
loginWithHuaweiIDResponse = controller.executeRequest(loginWithHuaweiIDRequest);
loginWithHuaweiIDCredential = loginWithHuaweiIDResponse?.data;
code = loginWithHuaweiIDCredential?.authorizationCode; // The authorization code can be parsed from the credential.
// Upload the authorization code to the app server. The app server then requests the UnionID/OpenID from the Account Kit server.

[h2]Obtaining User Information Associated with a HUAWEI ID

The @hms.core.authentication module provides the HUAWEI ID authorization and authorization revocation capabilities. These capabilities are used to obtain HUAWEI ID user information such as the avatar, nickname, risk level, and bound anonymous mobile number, and to manage the authorization relationship between users and apps.

You can use the authorization capability to request permission to access user information. After a user grants authorization, you can obtain an authorization code. The app server then uses the authorization code to call the APIs for obtaining a user-level credential and obtaining user information to request an access token and user information from the Account Kit server. After obtaining the user information, the app completes and displays the user's profile.

After obtaining a user's authorization, you can use the authorization revocation capability to proactively withdraw the user information access permission granted to the app.

You need to use HuaweiIDProvider to construct the authorization and revocation request objects, and use AuthenticationController to execute the requests. The pseudo-code of this process is as follows:

// Authorization:
provider = new authentication.HuaweiIDProvider();
authorizationWithHuaweiIDRequest = provider.createAuthorizationWithHuaweiIDRequest();
controller = new authentication.AuthenticationController(context);
authorizationWithHuaweiIDResponse = controller.executeRequest(authorizationWithHuaweiIDRequest);
authorizationWithHuaweiIDCredential = authorizationWithHuaweiIDResponse?.data;
code = authorizationWithHuaweiIDCredential?.authorizationCode; // The authorization code can be parsed from the credential.
// Upload the authorization code to the app server. The app server then requests user information from the Account Kit server.

// Authorization revocation:
cancelAuthorizationRequest = provider.createCancelAuthorizationRequest();
cancelAuthorizationResponse = controller.executeRequest(cancelAuthorizationRequest); // A response is returned when the authorization is revoked successfully. If the authorization fails to be revoked, an error code is returned.

[h2]Obtaining HUAWEI ID Sign-in Status

The @hms.core.authentication module provides the capability for obtaining the HUAWEI ID sign-in status to determine whether a HUAWEI ID is currently signed in to the system. After obtaining the user ID (UnionID/OpenID), you can use this capability to query the HUAWEI ID sign-in status, which does not require Internet connection.

You can create a request object for obtaining the HUAWEI ID sign-in status and pass the obtained user ID (UnionID/OpenID) to query the sign-in status. There are three statuses. For details, please refer to State.

[h2]Obtaining Mobile Number Consistency Status

The @hms.core.authentication module provides the capability for verifying the mobile number consistency status. It checks whether the mobile number obtained by an app through the capability of one-tap sign-in with HUAWEI ID is the same as the mobile number bound to the HUAWEI ID and the mobile number of the SIM card in the current device. When a user performs a high-risk operation after signing in to an app, you can use this capability to query the mobile number consistency status for security risk control.

You can create a request object and pass the obtained mobile number and user ID (UnionID/OpenID). Account Kit checks the consistency among the passed mobile number, mobile number bound to the HUAWEI ID, and mobile number of the SIM card in the current device. There are three consistency statuses. For details, please refer to ConsistencyRequest.

Since: 4.0.0(10)

Modules to Import

import { authentication } from '@kit.AccountKit';

HuaweiIDProvider

Authentication factory class of Account Kit, which mainly creates request objects for HUAWEI ID sign-in (LoginWithHuaweiIDRequest), authorization (AuthorizationWithHuaweiIDRequest), and authorization revocation (CancelAuthorizationRequest). You can modify object properties based on your service scenarios and then execute the requests using AuthenticationController.

In addition, the HuaweiIDProvider factory class provides the getHuaweiIDState and getMobileNumberConsistency methods to obtain the HUAWEI ID sign-in status and mobile number consistency status, respectively. You can construct StateRequest and ConsistencyRequest based on service information and use them as input parameters to call the preceding methods.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

Inheritance: HuaweiIDProvider inherits from AuthenticationProvider.

[h2]createLoginWithHuaweiIDRequest

createLoginWithHuaweiIDRequest(): LoginWithHuaweiIDRequest

Creates and returns a request object for HUAWEI ID sign-in (LoginWithHuaweiIDRequest).

After a request object is created and returned using this method, you can pass the object as an input parameter to the AuthenticationController.executeRequest method to execute the HUAWEI ID sign-in request and obtain the user ID (UnionID/OpenID).

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

Returns

Type Description
LoginWithHuaweiIDRequest Request object for HUAWEI ID sign-in.

Example:

For details, please refer to LoginWithHuaweiIDResponse.

[h2]createAuthorizationWithHuaweiIDRequest

createAuthorizationWithHuaweiIDRequest(): AuthorizationWithHuaweiIDRequest

Creates and returns a request object for HUAWEI ID authorization (AuthorizationWithHuaweiIDRequest).

After a request object is created and returned using this method, you can pass the object as an input parameter to the AuthenticationController.executeRequest method to execute the HUAWEI ID authorization request and obtain the user authorization credential.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

Returns

Type Description
AuthorizationWithHuaweiIDRequest Request object for HUAWEI ID authorization.

Example:

For details, please refer to AuthorizationWithHuaweiIDResponse.

[h2]createCancelAuthorizationRequest

createCancelAuthorizationRequest(): CancelAuthorizationRequest

Creates and returns a request object for HUAWEI ID authorization revocation (CancelAuthorizationRequest).

After a request object is created and returned using this method, you can pass the object as an input parameter to the AuthenticationController.executeRequest method to execute the authorization revocation request. This proactively withdraws the user information access permission granted to your app.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

Returns

Type Description
CancelAuthorizationRequest Request object for HUAWEI ID authorization revocation.

Example:

For details, please refer to CancelAuthorizationResponse.

[h2]getHuaweiIDState

getHuaweiIDState(request: StateRequest): Promise<StateResult>

Obtains the HUAWEI ID sign-in status. This method does not require Internet connection and uses a promise to return the result.

You can create a StateRequest object and pass the obtained user ID (UnionID/OpenID obtained through the capability of sign-in with a HUAWEI ID, obtaining user information associated with a HUAWEI ID, HUAWEI ID sign-in panel component, or HUAWEI ID sign-in button component). Account Kit checks whether a HUAWEI ID is signed in and whether the signed-in HUAWEI ID matches the passed user ID (UnionID/OpenID).

There are three statuses. For details, please refer to State.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 5.0.0(12)

Parameters

Parameter Type Mandatory Description
request StateRequest Yes Request object for obtaining the HUAWEI ID sign-in status.

Returns

Type Description
Promise<StateResult> Promise used to return the StateResult object.

Error codes:

For details about the error codes, please refer to Account Management Error Codes and ArkTS Error Codes.

ID Error Message
12300001 System service works abnormally.
1001502003 Invalid input parameter value.

Example:

import { authentication } from '@kit.AccountKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';

// Create request parameters.
const stateRequest: authentication.StateRequest = {
  idType: authentication.IdType.UNION_ID,
  idValue: 'xxx' // The value can be obtained through the HUAWEI ID sign-in API.
};
try {
  // Execute the request for obtaining the HUAWEI ID sign-in status and process the result.
  new authentication.HuaweiIDProvider().getHuaweiIDState(stateRequest).then((data: authentication.StateResult) => {
    hilog.info(0x0000, 'testTag', 'Succeeded in getting huaweiIdState result.');
    const state = data.state;
    // Process the state.
  }).catch((error: BusinessError) => {
    dealAllError(error);
  });
} catch (error) {
  dealAllError(error);
}

// Handle the error.
function dealAllError(error: BusinessError): void {
  hilog.error(0x0000, 'testTag', `Failed to get huaweiIdState, errorCode=${error.code}, errorMsg=${error.message}`);
}

[h2]getMobileNumberConsistency

getMobileNumberConsistency(request: ConsistencyRequest): Promise<ConsistencyResult>

Obtains the mobile number consistency status. This API uses a promise to return the result. It is used to check whether the mobile number obtained by an app through the capability of one-tap sign-in with HUAWEI ID is the same as the mobile number bound to the HUAWEI ID and the mobile number of the SIM card in the current device.

You can create a ConsistencyRequest object and pass the obtained mobile number and user ID (UnionID/OpenID). Account Kit checks the consistency among the passed mobile number, mobile number bound to the HUAWEI ID, and mobile number of the SIM card in the current device.

There are three consistency statuses. For details, please refer to ConsistencyState.

Before using this API for obtaining the mobile number consistency status, you need to request the quickLoginMobilePhone permission. For details, please refer to Prerequisites. If the permission request is incomplete or rejected, error code 1001502014 indicating that the app does not have the required scopes or permissions will be returned.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Device behavior differences: For 6.1.1(24) and earlier versions, this API is supported on phones, PCs/2-in-1 devices, and tablets. On other devices, it returns error code 801. For 26.0.0 and later versions, this API is supported on phones, PCs/2-in-1 devices, tablets, and TVs. On other devices, it returns error code 801.

Since: 5.0.0(12)

Parameters

Parameter Type Mandatory Description
request ConsistencyRequest Yes Request object for obtaining the mobile number consistency status.

Returns

Type Description
Promise<ConsistencyResult> Promise used to return the ConsistencyResult object.

Error codes:

For details about the error codes, please refer to Universal Error Codes and ArkTS Error Codes.

ID Error Message
401

Parameter error. Possible causes:

1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

801

Capability not supported. Function getMobileNumberConsistency can not work correctly due to limited device capabilities.

Applicable versions: 5.1.0(18)+

1001500001 Failed to check the fingerprint of the app bundle.
1001500004 The account does not support this function.
1001500005 This function is restricted from being called.
1001502001 The user has not logged in with HUAWEI ID.
1001502002 The application is not authorized.
1001502005 Network error.
1001502009 Internal error.
1001502014 The app does not have the required scopes or permissions.

Example:

import { authentication } from '@kit.AccountKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';

// Create request parameters.
const consistencyRequest: authentication.ConsistencyRequest = {
  idType: authentication.IdType.UNION_ID,
  idValue: 'xxx', // The value can be obtained through the HUAWEI ID sign-in API.
  mobileNumber: '+86xxxxxxxxxxx' // Mobile number in plaintext obtained through the function of one-tap sign-in with HUAWEI ID.
};
try {
  // Execute the request for obtaining the mobile number consistency status and process the result.
  new authentication.HuaweiIDProvider().getMobileNumberConsistency(consistencyRequest)
    .then((data: authentication.ConsistencyResult) => {
      hilog.info(0x0000, 'testTag', `Succeeded in getting getMobileNumberConsistency result = ${data.state}`);
      const state = data.state;
      // Process the state.
    })
    .catch((err: BusinessError) => {
      dealAllError(err);
    });
} catch (error) {
  dealAllError(error);
}

// Handle the error.
function dealAllError(error: BusinessError): void {
  hilog.error(0x0000, 'testTag',
    `Failed to get mobileNumberConsistency, errorCode=${error.code}, errorMsg=${error.message}`);
}

LoginWithHuaweiIDRequest

HUAWEI ID sign-in request class.

You can pass the object of the request class as a parameter to the AuthenticationController.executeRequest method to execute the HUAWEI ID sign-in request. If the request is successfully executed, the LoginWithHuaweiIDResponse object is returned, which provides the user ID (UnionID/OpenID).

You can modify the properties of this class to control whether the HUAWEI ID sign-in screen is displayed and to improve the security verification logic of your service. For details, please refer to the property descriptions.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

Inheritance: LoginWithHuaweiIDRequest inherits from AuthenticationRequest.

Name Type Read-Only Optional Description
forceLogin boolean No Yes

Indicates whether to display the HUAWEI ID sign-in screen when no HUAWEI ID is signed in.

- true: The HUAWEI ID sign-in screen will be displayed.

- false: The error code 1001502001 is returned, indicating that the user has not signed in with their HUAWEI ID.

If the user has signed in to the system with a HUAWEI ID, the HUAWEI ID sign-in screen will not be displayed regardless of whether the value is true or false.

The default value is true.

state string No Yes

state in the request. It can be compared with the state in the response to check whether the request corresponds to the current session, thereby preventing cross-site attacks.

The value can contain digits (0–9), letters (a–z or A–Z), dots (.), colons (:), slashes (/), and underscores (_). The length limit is 1 to 255 characters. The verification rule is ^[0-9a-zA-Z:/\.\-_]{1,255}$.

If this property is not passed or left empty, LoginWithHuaweiIDResponse will not contain state.

You are advised to use nonces and perform consistency verification. util.generateRandomUUID() is recommended.

nonce string No Yes

nonce in the request. It is compared with the nonce contained in the ID token in the response to check whether the request corresponds to the current session, thereby preventing replay attacks.

The value can contain digits (0–9), letters (a–z or A–Z), dots (.), colons (:), slashes (/), and underscores (_). The length limit is 1 to 255 characters. The verification rule is ^[0-9a-zA-Z:/\.\-_]{1,255}$.

If this property is not passed or is left empty, the default value of nonce in the ID token is default.

You are advised to use nonces and perform consistency verification. util.generateRandomUUID() is recommended.

idTokenSignAlgorithm IdTokenSignAlgorithm No Yes

ID token signing algorithm type. You can select an algorithm based on the security, performance, and system compatibility requirements.

The default value is PS256.

Example:

For details, please refer to LoginWithHuaweiIDResponse.

IdTokenSignAlgorithm

Enumerates the ID token signing algorithm types. An ID token can be encrypted using different algorithms defined in IdTokenSignAlgorithm. You can select an algorithm for your app based on the security, performance, and system compatibility requirements.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

Name Value Description
PS256 1 RSASSA-PSS uses SHA-256 together with MGF1 based on SHA-256. For security purposes, PS256 is recommended.
RS256 2 RSASSA-PKCS1-v1_5 uses SHA-256.

Example:

For details, please refer to LoginWithHuaweiIDResponse.

LoginWithHuaweiIDResponse

Response class for HUAWEI ID sign-in, which contains the data and state properties. data is the HUAWEI ID sign-in credential object, which contains data such as the authorization code and user ID (UnionID/OpenID). state is used to prevent cross-site attacks.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

Inheritance: LoginWithHuaweiIDResponse inherits from AuthenticationResponse.

Name Type Read-Only Optional Description
data LoginWithHuaweiIDCredential Yes Yes HUAWEI ID sign-in credential object, which contains data such as the authorization code and user ID (UnionID/OpenID).
state string Yes Yes

state in the response. It can be compared with the state in the request to check whether the request corresponds to the current session, thereby preventing cross-site attacks.

The value can contain digits (0–9), letters (a–z or A–Z), dots (.), colons (:), slashes (/), and underscores (_). The length limit is 1 to 255 characters. The verification rule is ^[0-9a-zA-Z:/\.\-_]{1,255}$.

Example:

import { authentication } from '@kit.AccountKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { util } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';

// Create a sign-in request and set parameters.
const loginRequest = new authentication.HuaweiIDProvider().createLoginWithHuaweiIDRequest();
// The default value is true. If no HUAWEI ID has signed in, the HUAWEI ID sign-in screen will be forcibly shown.
loginRequest.forceLogin = true;
loginRequest.idTokenSignAlgorithm = authentication.IdTokenSignAlgorithm.PS256;
loginRequest.state = util.generateRandomUUID(); // You are advised to use generateRandomUUID to generate the state, which can be used for consistency comparison to prevent cross-site attacks.

// Execute the sign-in request and process the result.
try {
  // The following provides only code snippets. Use it in the custom component instance and pass a valid context object.
  const controller = new authentication.AuthenticationController(this.getUIContext().getHostContext());
  controller.executeRequest(loginRequest, (error: BusinessError<Object>, data) => {
    if (error) {
      dealAllError(error);
      return;
    }
    const loginWithHuaweiIDResponse = data as authentication.LoginWithHuaweiIDResponse;
    const state = loginWithHuaweiIDResponse.state;
    // If state is empty, normalize it to an empty string.
    const normalizedRequestState = loginRequest.state || '';
    const normalizedState = state || '';
    if (normalizedRequestState !== normalizedState) {
      // The state is inconsistent. A cross-site attack may occur. Sign in again.
      hilog.error(0x0000, 'testTag', `Failed to login. The state is different, response state: ${state}`);
      return;
    }
    hilog.info(0x0000, 'testTag', 'Succeeded in login.');
    const loginWithHuaweiIDCredential = loginWithHuaweiIDResponse?.data;
    const authorizationCode = loginWithHuaweiIDCredential?.authorizationCode;
    const idToken = loginWithHuaweiIDCredential?.idToken;
    // Process the authorization code and ID token.
  });
} catch (error) {
  dealAllError(error);
}

// Handle the error.
function dealAllError(error: BusinessError<Object>): void {
  hilog.error(0x0000, 'testTag', `Failed to login. Code: ${error.code}, message: ${error.message}`);
  // In sign-in scenarios involving UI interactions, it is advised to guide users with the following error code prompts:
  if (error.code === ErrorCode.ERROR_CODE_LOGIN_OUT) {
    // HUAWEI ID not signed in. Use a HUAWEI ID to sign in and try again, or sign in to the app in another way.
  } else if (error.code === ErrorCode.ERROR_CODE_NETWORK_ERROR) {
    // Network error. Check the network connection and try again.
  } else if (error.code === ErrorCode.ERROR_CODE_INTERNAL_ERROR) {
    // Failed to sign in. Try another way.
  } else if (error.code === ErrorCode.ERROR_CODE_USER_CANCEL) {
    // Authorization canceled by the user.
  } else if (error.code === ErrorCode.ERROR_CODE_SYSTEM_SERVICE) {
    // System service exception. Try again later or sign in to the app in another way.
  } else if (error.code === ErrorCode.ERROR_CODE_REQUEST_REFUSE) {
    // Repeated request. No further action is needed.
  } else {
    // Failed to sign in. Try another way.
  }
}

export enum ErrorCode {
  // No HUAWEI ID has been signed in.
  ERROR_CODE_LOGIN_OUT = 1001502001,
  // Network error.
  ERROR_CODE_NETWORK_ERROR = 1001502005,
  // Internal error.
  ERROR_CODE_INTERNAL_ERROR = 1001502009,
  // Authorization canceled by the user.
  ERROR_CODE_USER_CANCEL = 1001502012,
  // System service exception.
  ERROR_CODE_SYSTEM_SERVICE = 12300001,
  // Repeated request.
  ERROR_CODE_REQUEST_REFUSE = 1001500002
}

LoginWithHuaweiIDCredential

Credential struct returned after a successful sign-in with a HUAWEI ID, which contains data such as authorization code and user ID (UnionID/OpenID).

However, it is recommended that you use the authorization code to obtain UnionID/OpenID through the interaction between your app server and the Account Kit server. This approach effectively mitigates security risks such as data interception and leakage. For details about the interaction process, please refer to Sign-in with a HUAWEI ID. In addition, this struct also provides OpenID and UnionID. If you choose to use the data directly, you are responsible for ensuring its security.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

Name Type Read-Only Optional Description
authorizationCode string Yes Yes Authorization code. It is used to obtain an access token. An authorization code is valid for 5 minutes and can be used only once. The value contains 1 to 1024 characters.
idToken string Yes Yes ID token, which is a user identity credential containing user information. It is a character string in JSON Web Token (JWT) format. JWT is an open standard (RFC 7519) that defines a secure method for transmitting information. For details, please refer to jwt.io. idToken is used to obtain certain user information and verify the signature. For details, please refer to When and How Can I Use the ID Token? The value contains 1 to 2048 characters.
openID string Yes No OpenID, which is a unique identifier for a HUAWEI ID user within an app or atomic service. A user has different OpenIDs across apps. For details about the format requirements, please refer to Formats of OpenID and UnionID.
unionID string Yes No UnionID, which is a unique identifier of a HUAWEI ID user under a developer account. A user has the same UnionID in different apps of the same developer. For details about the format requirements, please refer to Formats of OpenID and UnionID.

Example:

For details, please refer to LoginWithHuaweiIDResponse.

AuthorizationWithHuaweiIDRequest

HUAWEI ID authorization request class.

You can pass the object of the request class as a parameter to the AuthenticationController.executeRequest method to execute the HUAWEI ID authorization request. If the request is successfully executed, the AuthorizationWithHuaweiIDResponse object is returned, which provides the user authorization credential.

When the HUAWEI ID authorization request is executed and the forceAuthorization property is set to true, the HUAWEI ID sign-in screen is displayed if no HUAWEI ID is signed in, and the HUAWEI ID authorization screen is displayed if the user has signed in with a HUAWEI ID but has not authorized the app.

You can modify the properties of this class to set the scope of user information that your app needs to access, control whether the sign-in or authorization screen is displayed, and improve the security verification logic of your service. For details, please refer to the property descriptions.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

Inheritance: AuthorizationWithHuaweiIDRequest inherits from AuthenticationRequest.

Name Type Read-Only Optional Description
scopes string[] No Yes

Scope list, which defines the range of user information that the app needs to access. You can pass different combinations of scopes to request user data.

The scope types and their usage constraints are as follows:

- profile: scope for obtaining a HUAWEI ID user's avatar and nickname. (This scope is available for atomic services since API version 5.1.1(19) and must be used together with the supportAtomicService property.)

- openid: scope for obtaining the OpenID and UnionID of a HUAWEI ID user.

For details about the format requirements, please refer to Formats of OpenID and UnionID.

- phone: scope for obtaining the mobile number bound to a HUAWEI ID for quick verification.

Before using this scope, you must request the corresponding account permission. For details, please refer to Prerequisites. Atomic services cannot directly call this API to obtain the mobile number, but the quick mobile number verification button can be used for atomic services to obtain the mobile number. Mobile numbers of child accounts cannot be obtained via this scope.

- quickLoginAnonymousPhone: scope for obtaining anonymous mobile number bound to a HUAWEI ID. This scope is used for one-tap sign-in with HUAWEI ID, where the anonymous mobile number needs to be displayed on the screen for the user to confirm.

Before using this scope, you must request the corresponding account permission. For details, please refer to Prerequisites. This scope can only be used together with the openid scope. Mobile numbers cannot be obtained for wearables or HUAWEI IDs registered outside the Chinese mainland, and error code 1001500003 will be returned, indicating that the scopes or permissions are not supported.

Note: The returned anonymous mobile numbers that are registered in the Chinese mainland do not include the country code. For the mobile numbers of other countries and regions, the country/region code is included by default.

- riskLevel: scope for obtaining a HUAWEI ID user's risk level.

Before using this scope, you must request the corresponding account permission. For details, please refer to Prerequisites. This scope can only be used together with openid, phone, or profile. For HUAWEI IDs registered outside the Chinese mainland, the user risk level cannot be obtained.

Note: Atomic services do not support using the riskLevel scope in combination with phone. If an atomic service needs to use both scopes, refer to Mobile Number and Risk Level Retrieval Button of Scenario Fusion Kit.

- realNameAgeRange: scope for obtaining the age range of a HUAWEI ID user. Before using this scope, you must request the corresponding account permission. For details, please refer to Prerequisites.

scopes and permissions cannot both be empty. Otherwise, error code 1001502003 will be returned, indicating that the input parameter value is invalid. If an invalid scope (for example, empty value) is passed, the OpenID and UnionID are returned.

The default value is ['openid'].

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

permissions string[] No Yes

Permission list, which is used to obtain the authorization code and identity credential of a user.

The options of permissions are as follows:

- serviceauthcode: user authorization code. If the permissions property contains this type, the user authorization code will be returned in authorizationCode of the response struct.

- idtoken: user identity credential. If the permissions property contains this type, the ID token will be returned in idToken of the response struct.

Usage constraints:

- scopes and permissions cannot both be empty. Otherwise, error code 1001502003 will be returned, indicating that the input parameter value is invalid. If an invalid permission (for example, empty value) is passed, the OpenID and UnionID are returned.

The property is left empty by default, and no authorization code or user identity credentials are returned.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

forceAuthorization boolean No Yes

Indicates whether to show the sign-in or authorization screen when no HUAWEI ID is signed in or an app is not authorized.

- true: The screen will be displayed for sign-in or authorization.

- false: If no HUAWEI ID is signed in, error code 1001502001 will be returned. If a HUAWEI ID is signed in but the app is not authorized, error code 1001502002 will be returned.

The default value is true.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

state string No Yes

state in the request. It can be compared with the state in the response to check whether the request corresponds to the current session, thereby preventing cross-site attacks.

The value can contain digits (0–9), letters (a–z or A–Z), dots (.), colons (:), slashes (/), and underscores (_). The length limit is 1 to 255 characters. The verification rule is ^[0-9a-zA-Z:/\.\-_]{1,255}$.

If this property is not passed or left empty, AuthorizationWithHuaweiIDResponse will not contain state.

You are advised to use nonces and perform consistency verification. util.generateRandomUUID() is recommended.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

nonce string No Yes

nonce in the request. It is compared with the nonce contained in the ID token in the response to check whether the request corresponds to the current session, thereby preventing replay attacks.

The value can contain digits (0–9), letters (a–z or A–Z), dots (.), colons (:), slashes (/), and underscores (_). The length limit is 1 to 255 characters. The verification rule is ^[0-9a-zA-Z:/\.\-_]{1,255}$.

If this property is not passed or is left empty, the default value of nonce in the ID token is default.

You are advised to use nonces and perform consistency verification. util.generateRandomUUID() is recommended.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

idTokenSignAlgorithm IdTokenSignAlgorithm No Yes

ID token signing algorithm type. For details, please refer to IdTokenSignAlgorithm. You can select an algorithm based on the security, performance, and system compatibility requirements.

The default value is PS256.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

supportAtomicService boolean No Yes

Indicates whether atomic services are supported, to be specific, whether atomic services can obtain the user avatar and nickname if the profile scope is passed.

- If the value is true, the avatar and nickname can be obtained.

- If the value is false, error code 1001500003, indicating that the scopes or permissions are not supported, will be returned when the authorization request is executed.

The default value is false.

Since: 5.1.1(19)

Atomic service API: This API can be used in atomic services since API version 5.1.1(19).

Note: This property is used for atomic services.

Example:

For details, please refer to AuthorizationWithHuaweiIDResponse.

AuthorizationWithHuaweiIDResponse

HUAWEI ID authorization response class, which contains the data and state properties. data is the user authorization credential object, which contains data such as the authorization code and user information. state is used to prevent cross-site attacks.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

Inheritance: AuthorizationWithHuaweiIDResponse inherits from AuthenticationResponse.

Name Type Read-Only Optional Description
data AuthorizationWithHuaweiIDCredential Yes Yes HUAWEI ID authorization credential, which contains data such as the user authorization code and user information.
state string Yes Yes

state in the response. It can be compared with the state in the request to check whether the request corresponds to the current session, thereby preventing cross-site attacks.

The value can contain digits (0–9), letters (a–z or A–Z), dots (.), colons (:), slashes (/), and underscores (_). The length limit is 1 to 255 characters. The verification rule is ^[0-9a-zA-Z:/\.\-_]{1,255}$.

Example:

import { authentication } from '@kit.AccountKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { util } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';

// Create an authorization request and set parameters.
const authRequest = new authentication.HuaweiIDProvider().createAuthorizationWithHuaweiIDRequest();
// 'openid' is the default value and does not need to be set manually. To obtain other user information, pass the relevant scope. For details, please refer to the documentation of the AuthorizationWithHuaweiIDRequest class.
authRequest.scopes = ['openid'];
authRequest.permissions = ['idtoken', 'serviceauthcode'];
authRequest.forceAuthorization = true;
authRequest.state = util.generateRandomUUID(); // You are advised to use generateRandomUUID to generate the state, which can be used for consistency comparison to prevent cross-site attacks.
authRequest.idTokenSignAlgorithm = authentication.IdTokenSignAlgorithm.PS256;

// Execute the authorization request and process the result.
try {
  // The following provides only code snippets. Use it in the custom component instance and pass a valid context object.
  const controller = new authentication.AuthenticationController(this.getUIContext().getHostContext());
  controller.executeRequest(authRequest, (error: BusinessError<Object>, data) => {
    if (error) {
      dealAllError(error);
      return;
    }
    const authorizationWithHuaweiIDResponse = data as authentication.AuthorizationWithHuaweiIDResponse;
    const state = authorizationWithHuaweiIDResponse.state;
    // If state is empty, normalize it to an empty string.
    const normalizedRequestState = authRequest.state || '';
    const normalizedState = state || '';
    if (normalizedRequestState !== normalizedState) {
      // The state is inconsistent. A cross-site attack may occur. Re-authorization is required.
      hilog.error(0x0000, 'testTag', `Failed to authorize. The state is different, response state: ${state}`);
      return;
    }
    hilog.info(0x0000, 'testTag', 'Succeeded in authentication.');
    const authorizationWithHuaweiIDCredential = authorizationWithHuaweiIDResponse?.data;
    const authorizationCode = authorizationWithHuaweiIDCredential?.authorizationCode;
    const idToken = authorizationWithHuaweiIDCredential?.idToken;
    // Process information such as the authorization code and ID token.
  });
} catch (error) {
  dealAllError(error);
}

// Handle the error.
function dealAllError(error: BusinessError<Object>): void {
  hilog.error(0x0000, 'testTag', `Failed to obtain userInfo. Code: ${error.code}, message: ${error.message}`);
  // In scenarios involving UI interactions, it is advised to guide users with the following error code prompts:
  if (error.code === ErrorCode.ERROR_CODE_LOGIN_OUT) {
    // Not signed in with a HUAWEI ID. Sign in with a HUAWEI ID and try again.
  } else if (error.code === ErrorCode.ERROR_CODE_NETWORK_ERROR) {
    // Network error. Check the network connection and try again.
  } else if (error.code === ErrorCode.ERROR_CODE_USER_CANCEL) {
    // Authorization canceled by the user.
  } else if (error.code === ErrorCode.ERROR_CODE_SYSTEM_SERVICE) {
    // System service exception. Try again later.
  } else if (error.code === ErrorCode.ERROR_CODE_REQUEST_REFUSE) {
    // Repeated request. No further action is needed.
  } else {
    // Failed to obtain user information. Try again later.
  }
}

export enum ErrorCode {
  // No HUAWEI ID has been signed in.
  ERROR_CODE_LOGIN_OUT = 1001502001,
  // Network error.
  ERROR_CODE_NETWORK_ERROR = 1001502005,
  // Authorization canceled by the user.
  ERROR_CODE_USER_CANCEL = 1001502012,
  // System service exception.
  ERROR_CODE_SYSTEM_SERVICE = 12300001,
  // Repeated request.
  ERROR_CODE_REQUEST_REFUSE = 1001500002
}

AuthorizationWithHuaweiIDCredential

HUAWEI ID authorization credential. This struct is returned upon successful authorization and contains the authorization code and user information (such as avatar, nickname, email address, and anonymous mobile number).

However, it is recommended that you use the authorization code to obtain user information through the interaction between your app server and the Account Kit server. This approach effectively mitigates security risks such as data interception and leakage. For details about the interaction process, please refer to Obtaining User Information Associated with a HUAWEI ID. In addition, this struct also provides certain user information. If you choose to use the data directly, you are responsible for ensuring its security.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

Name Type Read-Only Optional Description
authorizationCode string Yes Yes

Authorization code. It is used to obtain an access token. An authorization code is valid for 5 minutes and can be used only once. The value contains 1 to 1024 characters.

Return scenario: This field is returned when permissions passed to AuthorizationWithHuaweiIDRequest contains 'serviceauthcode'.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

idToken string Yes Yes

ID token, which is a user identity credential in JWT string format. It is used to obtain certain user information and verify the signature. For details, please refer to When and How Can I Use the ID Token? The value contains 1 to 2048 characters.

Return scenario: This field is returned when permissions passed to AuthorizationWithHuaweiIDRequest contains 'idtoken'.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

openID string Yes Yes

OpenID, which is a unique identifier for a HUAWEI ID user within an app or atomic service. A user has different OpenIDs across apps. For details about the format requirements, please refer to Formats of OpenID and UnionID.

Return scenario: This field is returned by default.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

unionID string Yes Yes

UnionID, which is a unique identifier of a HUAWEI ID user under a developer account. A user has the same UnionID in different apps of the same developer. For details about the format requirements, please refer to Formats of OpenID and UnionID.

Return scenario: This field is returned by default.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

avatarUri string Yes Yes

User avatar link, which becomes invalid immediately after the user updates the avatar. To ensure that the avatar can be properly displayed, it is advised to download and save the avatar before using it. This prevents service processes from being affected due to invalid avatar links.

The value is not subject to length restrictions. Example: https://xxx/xxx

Return scenario: This field is returned when scopes passed to AuthorizationWithHuaweiIDRequest contains 'profile'.

Atomic service API: This API can be used in atomic services since API version 6.0.0(20).

nickName string Yes Yes

Nickname of a user. The value contains 2 to 20 characters.

Return scenario: This field is returned when scopes passed to AuthorizationWithHuaweiIDRequest contains 'profile'.

Atomic service API: This API can be used in atomic services since API version 6.0.0(20).

email string Yes Yes

Email address of a user. The value contains 4 to 254 characters.

Return scenario: This field is returned when scopes passed to AuthorizationWithHuaweiIDRequest contains 'email'.

Note: Atomic services do not support this field.

authorizedScopes string[] Yes Yes

Set of scopes that are successfully authorized. If multiple scopes are requested, the user can select some of them for authorization, and the set of scopes that are successfully authorized will be returned. Upon successful authorization, an authorization code will be returned, which can then be used to retrieve the corresponding user information. For details, please refer to the instructions specified in Overview.

Return scenario: By default, 'openid' is returned. If the user authorizes other scopes, all successfully authorized scopes are returned.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

extraInfo Record<string, Object> Yes Yes

Extended information. Currently, the following keys are supported:

- quickLoginAnonymousPhone: anonymous mobile number for one-tap sign-in. It is returned when scopes passed to AuthorizationWithHuaweiIDRequest contains 'quickLoginAnonymousPhone'.

- localNumberConsistency: indicates whether the mobile number bound to the HUAWEI ID is consistent with that of the SIM card in the device. It is returned when scopes passed to AuthorizationWithHuaweiIDRequest contains 'quickLoginAnonymousPhone'.

true: The mobile number bound to the HUAWEI ID is consistent with that of any SIM card in the current device.

false: The mobile number bound to the HUAWEI ID is different from the mobile number of any SIM card in the current device, or the device has no SIM card.

If code obfuscation has been enabled, the obfuscation trustlist needs to be configured to exclude the properties within it from being obfuscated.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

NOTE

- In 4.1.0(11) and earlier versions, the field type is object.

- Since version 5.0.0(12), the field type is Record<string, Object>.

Example:

For details, please refer to AuthorizationWithHuaweiIDResponse.

CancelAuthorizationRequest

Request class for revoking authorization. It contains the state property, which is used to prevent cross-site attacks. You can pass the object of the request class as a parameter to the AuthenticationController.executeRequest method to execute the authorization revocation request. This proactively withdraws the user information access permission granted to your app.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

Inheritance: CancelAuthorizationRequest inherits from AuthenticationRequest.

Name Type Read-Only Optional Description
state string No Yes

state in the request. It can be compared with the state in the response to check whether the request corresponds to the current session, thereby preventing cross-site attacks.

The value can contain digits (0–9), letters (a–z or A–Z), dots (.), colons (:), slashes (/), and underscores (_). The length limit is 1 to 255 characters. The verification rule is ^[0-9a-zA-Z:/\.\-_]{1,255}$.

You are advised to use nonces and perform consistency verification. util.generateRandomUUID() is recommended.

Example:

For details, please refer to CancelAuthorizationResponse.

CancelAuthorizationResponse

Response class for revoking authorization. It contains the state property, which is used to prevent cross-site attacks.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

Inheritance: CancelAuthorizationResponse inherits from AuthenticationResponse.

Name Type Read-Only Optional Description
state string Yes Yes state in the response. It can be compared with the state in the request to check whether the request corresponds to the current session, thereby preventing cross-site attacks. The value can contain digits (0–9), letters (a–z or A–Z), dots (.), colons (:), slashes (/), and underscores (_). The length limit is 1 to 255 characters. The verification rule is ^[0-9a-zA-Z:/\.\-_]{1,255}$.

Example:

import { authentication } from '@kit.AccountKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { util } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';

// Create an authorization revocation request and set parameters.
const cancelRequest = new authentication.HuaweiIDProvider().createCancelAuthorizationRequest();
cancelRequest.state = util.generateRandomUUID(); // You are advised to use generateRandomUUID to generate the state, which can be used for consistency comparison to prevent cross-site attacks.

// Execute the authorization revocation request and process the result.
try {
  // The following provides only code snippets. Use it in the custom component instance and pass a valid context object.
  const controller = new authentication.AuthenticationController(this.getUIContext().getHostContext());
  controller.executeRequest(cancelRequest, (error: BusinessError<Object>, data) => {
    if (error) {
      dealAllError(error);
      return;
    }
    const cancelAuthorizationResponse = data as authentication.CancelAuthorizationResponse;
    const state = cancelAuthorizationResponse.state;
    // If state is empty, normalize it to an empty string.
    const normalizedRequestState = cancelRequest.state || '';
    const normalizedState = state || '';
    if (normalizedRequestState !== normalizedState) {
      // The state is inconsistent. A cross-site attack may occur. Revoke the authorization again.
      hilog.error(0x0000, 'testTag', `Failed to cancel. The state is different, response state: ${state}`);
      return;
    }
    hilog.info(0x0000, 'testTag', 'Succeeded in canceling.');
  });
} catch (error) {
  dealAllError(error);
}

// Handle the error.
function dealAllError(error: BusinessError<Object>): void {
  hilog.error(0x0000, 'testTag', `Failed to cancel. Code: ${error.code}, message: ${error.message}`);
  // In sign-in scenarios involving UI interactions, it is advised to guide users with the following error code prompts:
  if (error.code === ErrorCode.ERROR_CODE_LOGIN_OUT) {
    // HUAWEI ID not signed in. Use a HUAWEI ID to sign in and try again, or sign in to the app in another way.
  } else if (error.code === ErrorCode.ERROR_CODE_NETWORK_ERROR) {
    // Network error. Check the network connection and try again.
  } else if (error.code === ErrorCode.ERROR_CODE_INTERNAL_ERROR) {
    // Failed to sign in. Try another way.
  } else if (error.code === ErrorCode.ERROR_CODE_USER_CANCEL) {
    // Authorization canceled by the user.
  } else if (error.code === ErrorCode.ERROR_CODE_SYSTEM_SERVICE) {
    // System service exception. Try again later or sign in to the app in another way.
  } else if (error.code === ErrorCode.ERROR_CODE_REQUEST_REFUSE) {
    // Repeated request. No further action is needed.
  } else {
    // Failed to sign in. Try another way.
  }
}

export enum ErrorCode {
  // No HUAWEI ID has been signed in.
  ERROR_CODE_LOGIN_OUT = 1001502001,
  // Network error.
  ERROR_CODE_NETWORK_ERROR = 1001502005,
  // Internal error.
  ERROR_CODE_INTERNAL_ERROR = 1001502009,
  // Authorization canceled by the user.
  ERROR_CODE_USER_CANCEL = 1001502012,
  // System service exception.
  ERROR_CODE_SYSTEM_SERVICE = 12300001,
  // Repeated request.
  ERROR_CODE_REQUEST_REFUSE = 1001500002
}

AuthenticationErrorCode

Enumerates error codes related to the authentication service APIs provided by Account Kit. Handle errors based on the error codes listed in the table below.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

Name Value Description
PACKAGE_FINGERPRINT_CHECK_ERROR 1001500001

The certificate fingerprint of the app fails to be verified.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

DUPLICATE_REQUEST_REJECTED 1001500002

Repeated request. No operation is needed to address this error. Your app needs to implement tap control to prevent consecutive taps from initiating the same request.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

SCOPE_OR_PERRMISSION_UNSUPPORTED 1001500003

The scopes or permissions are not supported.

Since: 5.0.0(12)

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

UNSUPPORTED 1001500004

This function is unavailable for the HUAWEI ID already signed in.

Since: 5.0.0(12)

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

REQUEST_RESTRICTED 1001500005

This function is restricted.

Since: 5.0.0(12)

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

ACCOUNT_NOT_LOGGED_IN 1001502001

The user has not signed in with their HUAWEI ID.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

APP_NOT_AUTHORIZED 1001502002

The app is not authorized.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

PARAMETER_INVALID 1001502003

Invalid input parameter value.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

NETWORK_ERROR 1001502005

A network error occurs.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

INTERNAL_ERROR 1001502009

Internal errors, such as Account Kit server errors.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

USER_CANCELED 1001502012

The user revokes authorization.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

SCOPE_OR_PERMISSION_NOT_REQUESTED 1001502014

The app does not have the required scopes or permissions.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

AuthenticationController

Controller class of Account Kit, which receives and executes requests for sign-in with a HUAWEI ID (LoginWithHuaweiIDRequest), authorization (AuthorizationWithHuaweiIDRequest), and authorization revocation (CancelAuthorizationRequest). You can pass the request object created by the HuaweiIDProvider factory class as a parameter to the executeRequest method to send the request to the Account Kit server.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

[h2]constructor

constructor(context?: common.Context)

Constructor of the controller class, which is used to construct an instance of the AuthenticationController class.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

Parameters

Parameter Type Mandatory Description
context common.Context No

Context. This parameter is mandatory when the HUAWEI ID sign-in or authorization screen needs to be started. Otherwise, error code 401 will be returned, indicating a parameter error.

The following contexts are supported for apps: UIAbilityContext and UIExtensionContext. Apps cannot use UIExtensionContext in non-full-screen components such as sheets, pop-ups, and sub-windows.

The following context is supported for atomic services: UIAbilityContext.

NOTE

- In version 4.0.0(10), the parameter type is UIAbilityContext.

- In 4.1.0(11) and later versions, the parameter type is Context.

Example:

Please refer to AuthenticationController.executeRequest.

[h2]executeRequest

executeRequest(request: AuthenticationRequest, callback: AsyncCallback<AuthenticationResponse, Record<string, Object>>): void

Executes a request. This API is a member function of the AuthenticationController class and uses a callback to return the result asynchronously. It receives and executes requests for sign-in with a HUAWEI ID (LoginWithHuaweiIDRequest), authorization (AuthorizationWithHuaweiIDRequest), and authorization revocation (CancelAuthorizationRequest), and returns the corresponding responses for sign-in with a HUAWEI ID (LoginWithHuaweiIDResponse), authorization (AuthorizationWithHuaweiIDResponse), and authorization revocation (CancelAuthorizationResponse).

After constructing a request object using createLoginWithHuaweiIDRequest, createAuthorizationWithHuaweiIDRequest, or createCancelAuthorizationRequest, you can call this API to execute the request.

When this API is called to execute a request for sign-in with a HUAWEI ID (LoginWithHuaweiIDRequest) or authorization (AuthorizationWithHuaweiIDRequest) and the forceLogin or forceAuthorization property is set to true, if no HUAWEI ID is signed in, the HUAWEI ID sign-in screen is displayed; if a HUAWEI ID is signed in but the app has not been authorized, the HUAWEI ID authorization screen is displayed. The screens allow users to remain active for an extended period. After the sign-in or authorization is complete, Account Kit returns a success result to the app. In other scenarios (for example, the user closes the screen), Account Kit returns the corresponding error code. You can plan the API calling time based on this rule to prevent service logic blocking caused by long response time.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

Parameters

Parameter Type Mandatory Description
request AuthenticationRequest Yes Request object for Account Kit's authentication service.
callback AsyncCallback<AuthenticationResponse, Record<string, Object>> Yes

Callback used to return the result of Account Kit's authentication service.

If the response data is successfully retrieved, err is undefined, and data is the AuthenticationResponse object. Otherwise, err is an error object.

NOTE

- In 4.1.0(11) and earlier versions, the parameter type is AsyncCallback<AuthenticationResponse, { [key: string]: Object }>.

- Since version 5.0.0(12), the parameter type is AsyncCallback<AuthenticationResponse, Record<string, Object>>.

Error codes:

For details about the error codes, please refer to Universal Error Codes, Account Management Error Codes, and ArkTS Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
12300001 System service works abnormally.
12300002

Invalid parameter.

Applicable versions: 4.0.0(10) to 4.1.0(11)

1001500001

Failed to check the fingerprint of the app bundle.

Applicable versions: 5.0.0(12)+

1001500002

This error code is reported when a request is already being processed.

Applicable versions: 5.0.0(12)+

1001500003

The scopes or permissions are not supported.

Applicable versions: 5.0.0(12)+

1001502001

The user has not logged in with HUAWEI ID.

Applicable versions: 5.0.0(12)+

1001502002

The application is not authorized.

Applicable versions: 5.0.0(12)+

1001502003

Invalid input parameter value.

Applicable versions: 5.0.0(12)+

1001502005

Network error.

Applicable versions: 5.0.0(12)+

1001502009

Internal error.

Applicable versions: 5.0.0(12)+

1001502012

The user canceled the authorization.

Applicable versions: 5.0.0(12)+

1001502014

The app does not have the required scopes or permissions.

Applicable versions: 5.0.0(12)+

Example:

import { authentication } from '@kit.AccountKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { util } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';

// Create an authorization request and set parameters.
const authRequest = new authentication.HuaweiIDProvider().createAuthorizationWithHuaweiIDRequest();
// 'openid' is the default value and does not need to be set manually. To obtain other user information, pass the relevant scope. For details, please refer to the documentation of the AuthorizationWithHuaweiIDRequest class.
authRequest.scopes = ['openid'];
authRequest.permissions = ['idtoken', 'serviceauthcode'];
authRequest.forceAuthorization = true;
authRequest.state = util.generateRandomUUID(); // You are advised to use generateRandomUUID to generate the state, which can be used for consistency comparison to prevent cross-site attacks.
authRequest.idTokenSignAlgorithm = authentication.IdTokenSignAlgorithm.PS256;

// Execute the authorization request and process the result.
try {
  // The following provides only code snippets. Use it in the custom component instance and pass a valid context object.
  const controller = new authentication.AuthenticationController(this.getUIContext().getHostContext());
  controller.executeRequest(authRequest, (error: BusinessError<Object>, data) => {
    if (error) {
      dealAllError(error);
      return;
    }
    const authorizationWithHuaweiIDResponse = data as authentication.AuthorizationWithHuaweiIDResponse;
    const state = authorizationWithHuaweiIDResponse.state;
    // If state is empty, normalize it to an empty string.
    const normalizedRequestState = authRequest.state || '';
    const normalizedState = state || '';
    if (normalizedRequestState !== normalizedState) {
      // The state is inconsistent. A cross-site attack may occur. Re-authorization is required.
      hilog.error(0x0000, 'testTag', `Failed to authorize. The state is different, response state: ${state}`);
      return;
    }
    hilog.info(0x0000, 'testTag', 'Succeeded in authentication.');
    const authorizationWithHuaweiIDCredential = authorizationWithHuaweiIDResponse?.data;
    const authorizationCode = authorizationWithHuaweiIDCredential?.authorizationCode;
    const idToken = authorizationWithHuaweiIDCredential?.idToken;
    // Process information such as the authorization code and ID token.
  });
} catch (error) {
  dealAllError(error);
}

// Handle the error.
function dealAllError(error: BusinessError<Object>): void {
  hilog.error(0x0000, 'testTag', `Failed to obtain userInfo. Code: ${error.code}, message: ${error.message}`);
  // In scenarios involving UI interactions, it is advised to guide users with the following error code prompts:
  if (error.code === ErrorCode.ERROR_CODE_LOGIN_OUT) {
    // Not signed in with a HUAWEI ID. Sign in with a HUAWEI ID and try again.
  } else if (error.code === ErrorCode.ERROR_CODE_NETWORK_ERROR) {
    // Network error. Check the network connection and try again.
  } else if (error.code === ErrorCode.ERROR_CODE_USER_CANCEL) {
    // Authorization canceled by the user.
  } else if (error.code === ErrorCode.ERROR_CODE_SYSTEM_SERVICE) {
    // System service exception. Try again later.
  } else if (error.code === ErrorCode.ERROR_CODE_REQUEST_REFUSE) {
    // Repeated request. No further action is needed.
  } else {
    // Failed to obtain user information. Try again later.
  }
}

export enum ErrorCode {
  // No HUAWEI ID has been signed in.
  ERROR_CODE_LOGIN_OUT = 1001502001,
  // Network error.
  ERROR_CODE_NETWORK_ERROR = 1001502005,
  // Authorization canceled by the user.
  ERROR_CODE_USER_CANCEL = 1001502012,
  // System service exception.
  ERROR_CODE_SYSTEM_SERVICE = 12300001,
  // Repeated request.
  ERROR_CODE_REQUEST_REFUSE = 1001500002
}

[h2]executeRequest

executeRequest(request: AuthenticationRequest): Promise<AuthenticationResponse>

Executes a request. This API is a member function of the AuthenticationController class. It receives and executes requests for sign-in with a HUAWEI ID (LoginWithHuaweiIDRequest), authorization (AuthorizationWithHuaweiIDRequest), and authorization revocation (CancelAuthorizationRequest), and returns the corresponding responses for sign-in with a HUAWEI ID (LoginWithHuaweiIDResponse), authorization (AuthorizationWithHuaweiIDResponse), and authorization revocation (CancelAuthorizationResponse). This API uses a promise to return the result.

After constructing a request object using createLoginWithHuaweiIDRequest, createAuthorizationWithHuaweiIDRequest, or createCancelAuthorizationRequest, you can call this API to execute the request.

When this API is called to execute a request for sign-in with a HUAWEI ID (LoginWithHuaweiIDRequest) or authorization (AuthorizationWithHuaweiIDRequest) and the forceLogin or forceAuthorization property is set to true, if no HUAWEI ID is signed in, the HUAWEI ID sign-in screen is displayed; if a HUAWEI ID is signed in but the app has not been authorized, the HUAWEI ID authorization screen is displayed. The screens allow users to remain active for an extended period. After the sign-in or authorization is complete, Account Kit returns a success result to the app. In other scenarios (for example, the user closes the screen), Account Kit returns the corresponding error code. You can plan the API calling time based on this rule to prevent service logic blocking caused by long response time.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

Parameters

Parameter Type Mandatory Description
request AuthenticationRequest Yes Request object for Account Kit's authentication service.

Returns

Type Description
Promise<AuthenticationResponse> Promise used to return the AuthenticationResponse object.

Error codes:

For details about the error codes, please refer to Universal Error Codes, Account Management Error Codes, and ArkTS Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
12300001 System service works abnormally.
12300002

Invalid parameter.

Applicable versions: 4.0.0(10) to 4.1.0(11)

1001500001

Failed to check the fingerprint of the app bundle.

Applicable versions: 5.0.0(12)+

1001500002

This error code is reported when a request is already being processed.

Applicable versions: 5.0.0(12)+

1001500003

The scopes or permissions are not supported.

Applicable versions: 5.0.0(12)+

1001502001

The user has not logged in with HUAWEI ID.

Applicable versions: 5.0.0(12)+

1001502002

The application is not authorized.

Applicable versions: 5.0.0(12)+

1001502003

Invalid input parameter value.

Applicable versions: 5.0.0(12)+

1001502005

Network error.

Applicable versions: 5.0.0(12)+

1001502009

Internal error.

Applicable versions: 5.0.0(12)+

1001502012

The user canceled the authorization.

Applicable versions: 5.0.0(12)+

1001502014

The app does not have the required scopes or permissions.

Applicable versions: 5.0.0(12)+

Example:

import { authentication } from '@kit.AccountKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { util } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';

// Create an authorization request and set parameters.
const authRequest = new authentication.HuaweiIDProvider().createAuthorizationWithHuaweiIDRequest();
// 'openid' is the default value and does not need to be set manually. To obtain other user information, pass the relevant scope. For details, please refer to the documentation of the AuthorizationWithHuaweiIDRequest class.
authRequest.scopes = ['openid'];
authRequest.permissions = ['idtoken', 'serviceauthcode'];
authRequest.forceAuthorization = true;
authRequest.state = util.generateRandomUUID(); // You are advised to use generateRandomUUID to generate the state, which can be used for consistency comparison to prevent cross-site attacks.
authRequest.idTokenSignAlgorithm = authentication.IdTokenSignAlgorithm.PS256;

// Execute the authorization request and process the result.
try {
  // The following provides only code snippets. Use it in the custom component instance and pass a valid context object.
  const controller = new authentication.AuthenticationController(this.getUIContext().getHostContext());
  controller.executeRequest(authRequest).then((data) => {
    const authorizationWithHuaweiIDResponse = data as authentication.AuthorizationWithHuaweiIDResponse;
    const state = authorizationWithHuaweiIDResponse.state;
    // If state is empty, normalize it to an empty string.
    const normalizedRequestState = authRequest.state || '';
    const normalizedState = state || '';
    if (normalizedRequestState !== normalizedState) {
      // The state is inconsistent. A cross-site attack may occur. Re-authorization is required.
      hilog.error(0x0000, 'testTag', `Failed to authorize. The state is different, response state: ${state}`);
      return;
    }
    hilog.info(0x0000, 'testTag', 'Succeeded in authentication.');
    const authorizationWithHuaweiIDCredential = authorizationWithHuaweiIDResponse?.data;
    const authorizationCode = authorizationWithHuaweiIDCredential?.authorizationCode;
    const idToken = authorizationWithHuaweiIDCredential?.idToken;
    // Process information such as the authorization code and ID token.
  }).catch((err: BusinessError) => {
    dealAllError(err);
  });
} catch (error) {
  dealAllError(error);
}

// Handle the error.
function dealAllError(error: BusinessError): void {
  hilog.error(0x0000, 'testTag', `Failed to obtain userInfo. Code: ${error.code}, message: ${error.message}`);
  // In scenarios involving UI interactions, it is advised to guide users with the following error code prompts:
  if (error.code === ErrorCode.ERROR_CODE_LOGIN_OUT) {
    // Not signed in with a HUAWEI ID. Sign in with a HUAWEI ID and try again.
  } else if (error.code === ErrorCode.ERROR_CODE_NETWORK_ERROR) {
    // Network error. Check the network connection and try again.
  } else if (error.code === ErrorCode.ERROR_CODE_USER_CANCEL) {
    // Authorization canceled by the user.
  } else if (error.code === ErrorCode.ERROR_CODE_SYSTEM_SERVICE) {
    // System service exception. Try again later.
  } else if (error.code === ErrorCode.ERROR_CODE_REQUEST_REFUSE) {
    // Repeated request. No further action is needed.
  } else {
    // Failed to obtain user information. Try again later.
  }
}

export enum ErrorCode {
  // No HUAWEI ID has been signed in.
  ERROR_CODE_LOGIN_OUT = 1001502001,
  // Network error.
  ERROR_CODE_NETWORK_ERROR = 1001502005,
  // Authorization canceled by the user.
  ERROR_CODE_USER_CANCEL = 1001502012,
  // System service exception.
  ERROR_CODE_SYSTEM_SERVICE = 12300001,
  // Repeated request.
  ERROR_CODE_REQUEST_REFUSE = 1001500002
}

AuthenticationRequest

Abstract base class for the HUAWEI ID authentication request. This class does not contain service-specific properties. For details about specific authentication requests, please refer to its derived classes, including LoginWithHuaweiIDRequest, AuthorizationWithHuaweiIDRequest and CancelAuthorizationRequest.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

AuthenticationResponse

Abstract base class for the HUAWEI ID authentication response. This class does not contain service-specific properties. For details about specific authentication responses, please refer to its derived classes, including LoginWithHuaweiIDResponse, AuthorizationWithHuaweiIDResponse and CancelAuthorizationResponse.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

AuthenticationProvider

Abstract base class for HUAWEI ID authentication factory. This class does not contain service-specific properties. For details about specific implementation, please refer to its derived class, that is HuaweiIDProvider.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 4.0.0(10)

IdType

Enumerates the ID types of a HUAWEI ID user.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 5.0.0(12)

Name Value Description
USER_ID 1

UID of a HUAWEI ID user.

Note: This parameter is available only to system apps.

OPEN_ID 2 OpenID of a HUAWEI ID user. For details about the format requirements, please refer to Formats of OpenID and UnionID.
UNION_ID 3 UnionID of a HUAWEI ID user. For details about the format requirements, please refer to Formats of OpenID and UnionID.

State

Enumerates the HUAWEI ID sign-in statuses. The statuses indicate whether a HUAWEI ID is signed in and whether the signed-in HUAWEI ID matches the passed user ID (UnionID/OpenID).

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 5.0.0(12)

Name Value Description
UNLOGGED_IN 0 No HUAWEI ID is signed in.
AUTHORIZED 1 A HUAWEI ID is signed in, and the passed UnionID/OpenID is the same as that of the current HUAWEI ID.
UNAUTHORIZED 2 A HUAWEI ID is signed in, but the passed UnionID/OpenID is different from that of the current HUAWEI ID.

StateRequest

Request for obtaining the HUAWEI ID sign-in status. The request must contain the idType and idValue properties, which are used to specify the ID type of the HUAWEI ID user and pass the user ID (UnionID/OpenID). You can pass the request object as a parameter to getHuaweiIDState to check whether a HUAWEI ID is signed in and whether the signed-in HUAWEI ID matches the passed user ID.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 5.0.0(12)

Name Type Read-Only Optional Description
idType IdType No No ID type of a HUAWEI ID user. For non-system apps, only IdType.UNION_ID and IdType.OPEN_ID are supported currently.
idValue string No No

UnionID/OpenID of a HUAWEI ID user. The ID type is specified by the idType property. This property cannot be empty. Otherwise, error code 1001502003 will be returned, indicating that the input parameter value is invalid. The value contains 1 to 256 characters.

The UnionID or OpenID can be obtained through the capability of sign-in with a HUAWEI ID, obtaining user information associated with a HUAWEI ID, HUAWEI ID sign-in panel component, or HUAWEI ID sign-in button component.

Example:

For details, please refer to getHuaweiIDState.

StateResult

Response for obtaining the HUAWEI ID sign-in status. It is the return value of the getHuaweiIDState method. The statuses indicate whether a HUAWEI ID is signed in and whether the signed-in HUAWEI ID matches the passed user ID (UnionID/OpenID).

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 5.0.0(12).

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 5.0.0(12)

Name Type Read-Only Optional Description
state State No No HUAWEI ID sign-in status.

Example:

For details, please refer to getHuaweiIDState.

ConsistencyState

Enumerates the mobile number consistency statuses, which indicate the consistency among the passed mobile number, mobile number bound to the HUAWEI ID, and mobile number of the SIM card in the current device. You can perform risk control based on the result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 5.0.0(12)

Name Value Description
CONSISTENT 0 A HUAWEI ID is signed in, and the passed mobile number is consistent with both the number bound to the HUAWEI ID and the number of any SIM card in the current device.
INCONSISTENT_WITH_DEVICES 1 A HUAWEI ID is signed in, and the passed mobile number is consistent with the number bound to the HUAWEI ID but different from the mobile number of any SIM card in the current device, or the device has no SIM card.
INCONSISTENT 2 A HUAWEI ID is signed in, but the passed mobile number is different from the number bound to the HUAWEI ID.

ConsistencyRequest

Request for obtaining the mobile number consistency status. The request must contain the idType, idValue, and mobileNumber properties, which specify the ID type (UnionID/OpenID) of a HUAWEI ID user, passed UnionID/OpenID value, and mobile number, respectively. You can pass the request object as a parameter to getMobileNumberConsistency to check the consistency among the passed mobile number, mobile number bound to the HUAWEI ID, and mobile number of the SIM card in the current device.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 5.0.0(12)

Name Type Read-Only Optional Description
idType IdType No No ID type of a HUAWEI ID user. For non-system apps, only IdType.UNION_ID and IdType.OPEN_ID are supported currently.
idValue string No No

UnionID/OpenID of a HUAWEI ID user. The ID type is specified by the idType property. The value contains 1 to 256 characters.

The UnionID or OpenID can be obtained through the capability of sign-in with a HUAWEI ID, obtaining user information associated with a HUAWEI ID, HUAWEI ID sign-in panel component, or HUAWEI ID sign-in button component.

mobileNumber string No No

Mobile number (plaintext) obtained through the one-tap sign-in function of the LoginWithHuaweiIDButton component. The country/region code must be included in the passed mobile number (for example, "+86" for mobile numbers registered in the Chinese mainland). Here is an example: +86xxxxxxxxxxx (plaintext mobile number).

The value contains 1 to 256 characters.

Example:

For details, please refer to getMobileNumberConsistency.

ConsistencyResult

Response for obtaining the mobile number consistency status. It is the return value of the getMobileNumberConsistency method, which indicates the consistency among the passed mobile number, mobile number bound to the HUAWEI ID, and mobile number of the SIM card in the current device. You can perform risk control based on the result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.Auth

Since: 5.0.0(12)

Name Type Read-Only Optional Description
state ConsistencyState No No Mobile number consistency status.

Example:

For details, please refer to getMobileNumberConsistency.