@ohos.userIAM.userAuth (User Authentication)
The userAuth module provides APIs for user authentication, which applies to scenarios such as device unlocking, payment, and application login.
NOTE
The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
Modules to Import
import { userAuth } from '@kit.UserAuthenticationKit';
Constant
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Type | Value | Description |
|---|---|---|---|
| MAX_ALLOWABLE_REUSE_DURATION12+ | number | 300000 | Maximum reuse duration of the unlock authentication result, in milliseconds. The value is 300000. Atomic service API: This API can be used in atomic services since API version 12. |
| PERMANENT_LOCKOUT_DURATION22+ | number | 0x7fffffff | Permanent lockout duration, in milliseconds. The value is 0x7fffffff. Atomic service API: This API can be used in atomic services since API version 22. |
AuthLockState22+
Enumerates the lockout status of an identity authentication type.
Atomic service API: This API can be used in atomic services since API version 22.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| isLocked | boolean | No | No | Whether the authentication is locked. true means yes; false otherwise. |
| remainingAuthAttempts | number | No | No | Number of remaining attempts before the authentication is locked. The maximum value is 5. |
| lockoutDuration | number | No | No | Remaining lockout duration, in milliseconds. If the authentication is permanently locked, the value is PERMANENT_LOCKOUT_DURATION. You need to unlock it using the PIN. |
UserAuthTipCode20+
Enumerates the intermediate states of identity authentication.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Value | Description |
|---|---|---|
| COMPARE_FAILURE | 1 | The authentication failed. |
| TIMEOUT | 2 | The authentication has timed out. |
| TEMPORARILY_LOCKED | 3 | The authentication is temporarily locked. |
| PERMANENTLY_LOCKED | 4 | The authentication is permanently locked. |
| WIDGET_LOADED | 5 | The identity authentication page is loaded. |
| WIDGET_RELEASED | 6 | The current identity authentication page is switched to another authentication page or the identity authentication component is closed. |
| COMPARE_FAILURE_WITH_FROZEN | 7 | Authentication is locked after a failed attempt. |
EnrolledState12+
Represents the state of a credential enrolled.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| credentialDigest | number | No | No | Credential digest, which is randomly generated when a credential is added. |
| credentialCount | number | No | No | Number of enrolled credentials. |
ReuseMode12+
Enumerates the modes for reusing authentication results.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Value | Description |
|---|---|---|
| AUTH_TYPE_RELEVANT | 1 | The device unlock authentication result can be reused within the validity period if the authentication type matches any of the authentication types specified for this authentication. Atomic service API: This API can be used in atomic services since API version 12. |
| AUTH_TYPE_IRRELEVANT | 2 | The device unlock authentication result can be reused within the validity period regardless of the authentication type. Atomic service API: This API can be used in atomic services since API version 12. |
| CALLER_IRRELEVANT_AUTH_TYPE_RELEVANT14+ | 3 | Any identity authentication result (including device unlock authentication result) can be reused within the validity period if the authentication type matches any of the authentication types specified for this authentication. Atomic service API: This API can be used in atomic services since API version 14. |
| CALLER_IRRELEVANT_AUTH_TYPE_IRRELEVANT14+ | 4 | Any identity authentication result (including device unlock authentication result) can be reused within the validity period regardless of the authentication type. Atomic service API: This API can be used in atomic services since API version 14. |
ReuseUnlockResult12+
Represents information about the authentication result reuse.
NOTE
If the credential changes within the reuse duration after a successful identity authentication (including device unlock authentication), the authentication result can still be reused and the actual EnrolledState is returned in the authentication result. If the credential used for the previous authentication has been deleted when the authentication result is used:
- If the deleted credential is face or fingerprint, the authentication result can still be reused, but credentialCount and credentialDigest in the EnrolledState returned are both 0.
- If the deleted credential is a lock screen password, the reuse will fail.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| reuseMode | ReuseMode | No | No | Authentication result reuse mode. |
| reuseDuration | number | No | No | Reuse duration of the authentication result, in milliseconds. The value must be greater than 0 and the maximum value is MAX_ALLOWABLE_REUSE_DURATION. |
userAuth.getAuthLockState22+
getAuthLockState(authType: UserAuthType): Promise<AuthLockState>
Queries the lockout state of the specified authentication type. This API uses a promise to return the result.
Required permissions: ohos.permission.ACCESS_BIOMETRIC
Atomic service API: This API can be used in atomic services since API version 22.
System capability: SystemCapability.UserIAM.UserAuth.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| authType | UserAuthType | Yes | Authentication type. |
Return value
| Type | Description |
|---|---|
| Promise<AuthLockState> | Promise used to return the result. An error is reported when the operation fails. |
Error codes
For details about the error codes, see Universal Error Codes and User Authentication Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 12500002 | General operation error. |
| 12500005 | The authentication type is not supported. |
| 12500008 | The parameter is out of range. |
| 12500010 | The type of credential has not been enrolled. |
Example
import { userAuth } from '@kit.UserAuthenticationKit';
import { BusinessError } from '@kit.BasicServicesKit';
let queryType = userAuth.UserAuthType.PIN;
let authLockState : userAuth.AuthLockState = {
isLocked : false,
remainingAuthAttempts : 0,
lockoutDuration : 0
}
userAuth.getAuthLockState(queryType)
.then((result: userAuth.AuthLockState) => {
authLockState = result;
console.info('get auth lock state successfully.');
})
.catch((err: BusinessError) => {
console.info(`get auth lock state failed, err code is : ${err?.code}, err message is : ${err?.message}`);
})
userAuth.getEnrolledState12+
getEnrolledState(authType: UserAuthType): EnrolledState
Obtains the credential state.
Required permissions: ohos.permission.ACCESS_BIOMETRIC
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.UserIAM.UserAuth.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| authType | UserAuthType | Yes | Authentication type. |
Return value
| Type | Description |
|---|---|
| EnrolledState | Credential state obtained if the operation is successful. |
Error codes
For details about the error codes, see Universal Error Codes and User Authentication Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. |
| 12500002 | General operation error. |
| 12500005 | The authentication type is not supported. |
| 12500010 | The type of credential has not been enrolled. |
Example
import { userAuth } from '@kit.UserAuthenticationKit';
import { BusinessError } from '@kit.BasicServicesKit';
try {
let enrolledState = userAuth.getEnrolledState(userAuth.UserAuthType.FACE);
console.info('get current enrolled state successfully.');
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`get current enrolled state failed, Code is ${err?.code}, message is ${err?.message}`);
}
AuthParam10+
Defines the user authentication parameters.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| challenge | Uint8Array | No | No | Random challenge value, which can be used to prevent replay attacks. It cannot exceed 32 bytes and can be passed in Uint8Array([]) format. Atomic service API: This API can be used in atomic services since API version 12. |
| authType | UserAuthType[] | No | No | Authentication type list, which specifies the types of authentication provided on the user authentication page. Atomic service API: This API can be used in atomic services since API version 12. |
| authTrustLevel | AuthTrustLevel | No | No | Authentication trust level. For details, see Principles for Classifying Biometric Authentication Trust Levels. Atomic service API: This API can be used in atomic services since API version 12. |
| reuseUnlockResult12+ | ReuseUnlockResult | No | Yes | Information about the authentication result reuse. By default, the result cannot be reused. Atomic service API: This API can be used in atomic services since API version 12. |
| skipLockedBiometricAuth20+ | boolean | No | Yes | Whether to skip the authentication mode that has been locked and automatically switch to another authentication mode. If no authentication mode can be switched to, the component is disabled and an authentication freezing error code is returned. true: When biometric authentication is frozen, the system skips the countdown page and directly switches to another authentication mode. false (default): The countdown page is not skipped. Atomic service API: This API can be used in atomic services since API version 20. |
WidgetParam10+
Represents the information presented on the user authentication page.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| title | string | No | No | Title of the user authentication page, which cannot be empty or exceed 500 characters. You are advised to set it to the authentication purpose, such as payment or application login. Atomic service API: This API can be used in atomic services since API version 12. |
| navigationButtonText | string | No | Yes | Text on the navigation button. It cannot exceed 60 characters. It is supported in single fingerprint or facial authentication before API version 18. Since API version 18, it is also supported in combined facial and fingerprint authentication. By default, the custom navigation button is not displayed. Atomic service API: This API can be used in atomic services since API version 12. |
| uiContext18+ | Context | No | Yes | Whether to display the authentication dialog box as an application modal dialog. This mode is applicable only to 2-in-1 devices. If this mode is not used or other types of devices are used, the authentication dialog box is displayed as a system modal dialog. By default, the authentication dialog box is displayed as a system modal dialog. Atomic service API: This API can be used in atomic services since API version 18. |
UserAuthResult10+
Represents the user authentication result. If the authentication is successful, the authentication type and token information are returned.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| result | number | No | No | User authentication result. If the authentication is successful, SUCCESS is returned. Otherwise, an error code is returned. For details, see UserAuthResultCode. |
| token | Uint8Array | No | Yes | Authentication token information. The value can contain a maximum of 1024 bytes. |
| authType | UserAuthType | No | Yes | Authentication type. |
| enrolledState12+ | EnrolledState | No | Yes | Credential state. |
IAuthCallback10+
Provides callbacks to return the authentication result.
onResult10+
onResult(result: UserAuthResult): void
Called to return the authentication result. If the authentication is successful, UserAuthResult contains the token information.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.UserIAM.UserAuth.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| result | UserAuthResult | Yes | Authentication result. |
Example 1
Initiate a lock screen password authentication request at ATL3 or higher.
import { BusinessError } from '@kit.BasicServicesKit';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { userAuth } from '@kit.UserAuthenticationKit';
try {
const rand = cryptoFramework.createRandom();
const len: number = 16;
let randData: Uint8Array | null = null;
let retryCount = 0;
while(retryCount < 3){
randData = rand?.generateRandomSync(len)?.data;
if(randData){
break;
}
retryCount++;
}
if(!randData){
return;
}
const authParam: userAuth.AuthParam = {
challenge: randData,
authType: [userAuth.UserAuthType.PIN],
authTrustLevel: userAuth.AuthTrustLevel.ATL3,
};
const widgetParam: userAuth.WidgetParam = {
title: 'Enter password',
};
const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
console.info('get userAuth instance successfully.');
// The authentication result is returned by onResult only after the authentication is started by start() of UserAuthInstance.
userAuthInstance.on('result', {
onResult (result) {
console.info(`userAuthInstance callback result = ${result.result}`);
}
});
console.info('auth on successfully.');
userAuthInstance.start();
console.info('auth start successfully.');
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`auth failed. Code is ${err?.code}, message is ${err?.message}`);
}
Example 2
Initiate a lock screen password authentication request at ATL3 or higher, and enable the authentication result to be reused for the same type of authentication within the maximum reuse duration of device unlocking.
import { BusinessError } from '@kit.BasicServicesKit';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { userAuth } from '@kit.UserAuthenticationKit';
let reuseUnlockResult: userAuth.ReuseUnlockResult = {
reuseMode: userAuth.ReuseMode.AUTH_TYPE_RELEVANT,
reuseDuration: userAuth.MAX_ALLOWABLE_REUSE_DURATION,
}
try {
const rand = cryptoFramework.createRandom();
const len: number = 16;
let randData: Uint8Array | null = null;
let retryCount = 0;
while(retryCount < 3){
randData = rand?.generateRandomSync(len)?.data;
if(randData){
break;
}
retryCount++;
}
if(!randData){
return;
}
const authParam: userAuth.AuthParam = {
challenge: randData,
authType: [userAuth.UserAuthType.PIN],
authTrustLevel: userAuth.AuthTrustLevel.ATL3,
reuseUnlockResult: reuseUnlockResult,
};
const widgetParam: userAuth.WidgetParam = {
title: 'Enter password',
};
const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
console.info('get userAuth instance successfully.');
// The authentication result is returned by onResult only after the authentication is started by start() of UserAuthInstance.
userAuthInstance.on('result', {
onResult (result) {
console.info(`userAuthInstance callback result = ${result.result}`);
}
});
console.info('auth on successfully.');
userAuthInstance.start();
console.info('auth start successfully.');
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`auth failed. Code is ${err?.code}, message is ${err?.message}`);
}
Example 3
Initiate a lock screen password authentication request at ATL3 or higher, and enable the authentication result to be reused for any type of authentication within the maximum reuse duration of any application.
import { BusinessError } from '@kit.BasicServicesKit';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { userAuth } from '@kit.UserAuthenticationKit';
let reuseUnlockResult: userAuth.ReuseUnlockResult = {
reuseMode: userAuth.ReuseMode.CALLER_IRRELEVANT_AUTH_TYPE_RELEVANT,
reuseDuration: userAuth.MAX_ALLOWABLE_REUSE_DURATION,
}
try {
const rand = cryptoFramework.createRandom();
const len: number = 16;
let randData: Uint8Array | null = null;
let retryCount = 0;
while(retryCount < 3){
randData = rand?.generateRandomSync(len)?.data;
if(randData){
break;
}
retryCount++;
}
if(!randData){
return;
}
const authParam: userAuth.AuthParam = {
challenge: randData,
authType: [userAuth.UserAuthType.PIN],
authTrustLevel: userAuth.AuthTrustLevel.ATL3,
reuseUnlockResult: reuseUnlockResult,
};
const widgetParam: userAuth.WidgetParam = {
title: 'Enter password',
};
const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
console.info('get userAuth instance successfully.');
// The authentication result is returned by onResult only after the authentication is started by start() of UserAuthInstance.
userAuthInstance.on('result', {
onResult (result) {
console.info(`userAuthInstance callback result = ${result.result}`);
}
});
console.info('auth on successfully.');
userAuthInstance.start();
console.info('auth start successfully.');
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`auth failed. Code is ${err?.code}, message is ${err?.message}`);
}
AuthTipInfo20+
Represents the intermediate authentication status.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| tipType | UserAuthType | No | No | Authentication type of the intermediate status. |
| tipCode | UserAuthTipCode | No | No | Intermediate status. |
AuthTipCallback20+
type AuthTipCallback = (authTipInfo: AuthTipInfo) => void
Defines the callback to return the intermediate authentication status.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.UserIAM.UserAuth.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| authTipInfo | AuthTipInfo | Yes | Intermediate authentication status. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { userAuth } from '@kit.UserAuthenticationKit';
try {
const rand = cryptoFramework.createRandom();
const len: number = 16;
let randData: Uint8Array | null = null;
let retryCount = 0;
while(retryCount < 3){
randData = rand?.generateRandomSync(len)?.data;
if(randData){
break;
}
retryCount++;
}
if(!randData){
return;
}
const authParam: userAuth.AuthParam = {
challenge: randData,
authType: [userAuth.UserAuthType.PIN],
authTrustLevel: userAuth.AuthTrustLevel.ATL3,
};
const widgetParam: userAuth.WidgetParam = {
title: 'Enter password',
};
const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
console.info('get userAuth instance successfully.');
// The intermediate authentication status is returned by onAuthTip only after the authentication is started by start() of UserAuthInstance.
userAuthInstance.on('authTip', (authTipInfo: userAuth.AuthTipInfo) => {
console.info('userAuthInstance callback');
});
console.info('auth on successfully.');
userAuthInstance.start();
console.info('auth start successfully.');
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`auth failed. Code is ${err?.code}, message is ${err?.message}`);
}
UserAuthInstance10+
Provides APIs for user authentication. The user authentication widget is supported.
Before using the APIs of UserAuthInstance, you must obtain a UserAuthInstance instance by using getUserAuthInstance.
on('result')10+
on(type: 'result', callback: IAuthCallback): void
Subscribes to the user authentication result. This API is used to obtain the final identity authentication result after the user completes identity authentication interaction with the authentication component. Before the authentication component disappears, the authentication failure attempts are not returned through this API. To perceive each authentication failure, use the on('authTip') API for subscription.
NOTE
On PCs/2-in-1 devices, if an application initiates authentication in an application modal dialog (that is, a valid uiContext is passed when the user API parameter widgetParam is configured) and receives the authentication result, and if other windows need to be displayed, the application needs to obtain the flag message released by the component pop-up window and subscribe to the component release message (authTipInfo.tipCode = UserAuthTipCode.WIDGET_RELEASED) through the on('authTip') API.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.UserIAM.UserAuth.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | 'result' | Yes | Event type. The value is result, which indicates the authentication result. |
| callback | IAuthCallback | Yes | Callback used to return the user authentication result. |
Error codes
For details about the error codes, see Universal Error Codes and User Authentication Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
| 12500002 | General operation error. |
Example 1
Perform user identity authentication in a system modal dialog.
import { BusinessError } from '@kit.BasicServicesKit';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { userAuth } from '@kit.UserAuthenticationKit';
try {
const rand = cryptoFramework.createRandom();
const len: number = 16;
let randData: Uint8Array | null = null;
let retryCount = 0;
while(retryCount < 3){
randData = rand?.generateRandomSync(len)?.data;
if(randData){
break;
}
retryCount++;
}
if(!randData){
return;
}
const authParam: userAuth.AuthParam = {
challenge: randData,
authType: [userAuth.UserAuthType.PIN],
authTrustLevel: userAuth.AuthTrustLevel.ATL3,
};
const widgetParam: userAuth.WidgetParam = {
title: 'Enter password',
};
const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
console.info('get userAuth instance successfully.');
// The authentication result is returned by onResult only after the authentication is started by start() of UserAuthInstance.
userAuthInstance.on('result', {
onResult (result) {
console.info(`userAuthInstance callback result = ${result.result}`);
}
});
console.info('auth on successfully.');
userAuthInstance.start();
console.info('auth start successfully.');
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`auth failed. Code is ${err?.code}, message is ${err?.message}`);
}
Example 2
Perform user identity authentication in an application modal dialog.
import { BusinessError } from '@kit.BasicServicesKit';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { userAuth } from '@kit.UserAuthenticationKit';
@Entry
@Component
struct Index {
modelApplicationAuth(): void {
try {
const rand = cryptoFramework.createRandom();
const len: number = 16;
let randData: Uint8Array | null = null;
let retryCount = 0;
while(retryCount < 3){
randData = rand?.generateRandomSync(len)?.data;
if(randData){
break;
}
retryCount++;
}
if(!randData){
return;
}
const authParam: userAuth.AuthParam = {
challenge: randData,
authType: [userAuth.UserAuthType.PIN],
authTrustLevel: userAuth.AuthTrustLevel.ATL3,
};
const uiContext: UIContext = this.getUIContext();
const context: Context | undefined = uiContext.getHostContext();
const widgetParam: userAuth.WidgetParam = {
title: 'Enter password',
uiContext: context,
};
const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
console.info('get userAuth instance successfully.');
// The authentication result is returned by onResult only after the authentication is started by start() of UserAuthInstance.
userAuthInstance.on('result', {
onResult (result) {
console.info(`userAuthInstance callback result =${result.result}`);
}
});
console.info('auth on successfully.');
userAuthInstance.start();
console.info('auth start successfully.');
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`auth failed. Code is ${err?.code}, message is ${err?.message}`);
}
}
build() {
Column() {
Button('start auth')
.onClick(() => {
this.modelApplicationAuth();
})
}
}
}
off('result')10+
off(type: 'result', callback?: IAuthCallback): void
Unsubscribes from the user authentication result.
NOTE
The UserAuthInstance instance used to invoke this API must be the one used to subscribe to the event.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.UserIAM.UserAuth.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | 'result' | Yes | Event type. The value is result, which indicates the authentication result. |
| callback | IAuthCallback | No | Callback used to return the user authentication result. If this parameter is not passed, the value passed when the on('result') API is called is used by default. |
Error codes
For details about the error codes, see Universal Error Codes and User Authentication Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
| 12500002 | General operation error. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { userAuth } from '@kit.UserAuthenticationKit';
try {
const rand = cryptoFramework.createRandom();
const len: number = 16;
let randData: Uint8Array | null = null;
let retryCount = 0;
while(retryCount < 3){
randData = rand?.generateRandomSync(len)?.data;
if(randData){
break;
}
retryCount++;
}
if(!randData){
return;
}
const authParam: userAuth.AuthParam = {
challenge: randData,
authType: [userAuth.UserAuthType.PIN],
authTrustLevel: userAuth.AuthTrustLevel.ATL3,
};
const widgetParam: userAuth.WidgetParam = {
title: 'Enter password',
};
const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
console.info('get userAuth instance successfully.');
userAuthInstance.off('result', {
onResult (result) {
console.info(`auth off result = ${result.result}`);
}
});
console.info('auth off successfully.');
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`auth failed. Code is ${err?.code}, message is ${err?.message}`);
}
start10+
start(): void
Starts authentication.
NOTE
Each UserAuthInstance can be used for authentication only once.
Required permissions: ohos.permission.ACCESS_BIOMETRIC or ohos.permission.USER_AUTH_FROM_BACKGROUND (available only for system applications)
Starting from API version 20, only system applications can apply for the ohos.permission.USER_AUTH_FROM_BACKGROUND permission.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.UserIAM.UserAuth.Core
Error codes
For details about the error codes, see Universal Error Codes and User Authentication Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. Possible causes: 1.No permission to access biometric. 2.No permission to start authentication from background. |
| 401 | Parameter error. Possible causes: 1.Incorrect parameter types. |
| 12500002 | General operation error. |
| 12500003 | Authentication canceled. |
| 12500005 | The authentication type is not supported. |
| 12500006 | The authentication trust level is not supported. |
| 12500009 | Authentication is locked out. |
| 12500010 | The type of credential has not been enrolled. |
| 12500011 | Switched to the customized authentication process. |
| 12500013 | Operation failed because of PIN expired. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { userAuth } from '@kit.UserAuthenticationKit';
try {
const rand = cryptoFramework.createRandom();
const len: number = 16;
let randData: Uint8Array | null = null;
let retryCount = 0;
while(retryCount < 3){
randData = rand?.generateRandomSync(len)?.data;
if(randData){
break;
}
retryCount++;
}
if(!randData){
return;
}
const authParam: userAuth.AuthParam = {
challenge: randData,
authType: [userAuth.UserAuthType.PIN],
authTrustLevel: userAuth.AuthTrustLevel.ATL3,
};
const widgetParam: userAuth.WidgetParam = {
title: 'Enter password',
};
const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
console.info('get userAuth instance successfully.');
userAuthInstance.start();
console.info('auth start successfully.');
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`auth failed. Code is ${err?.code}, message is ${err?.message}`);
}
cancel10+
cancel(): void
Cancels this authentication.
NOTE
UserAuthInstance must be the instance being authenticated.
Required permissions: ohos.permission.ACCESS_BIOMETRIC
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.UserIAM.UserAuth.Core
Error codes
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. Possible causes: 1.Incorrect parameter types. |
| 12500002 | General operation error. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { userAuth } from '@kit.UserAuthenticationKit';
try {
const rand = cryptoFramework.createRandom();
const len: number = 16;
let randData: Uint8Array | null = null;
let retryCount = 0;
while(retryCount < 3){
randData = rand?.generateRandomSync(len)?.data;
if(randData){
break;
}
retryCount++;
}
if(!randData){
return;
}
const authParam : userAuth.AuthParam = {
challenge: randData,
authType: [userAuth.UserAuthType.PIN],
authTrustLevel: userAuth.AuthTrustLevel.ATL3,
};
const widgetParam: userAuth.WidgetParam = {
title: 'Enter password',
};
const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
console.info('get userAuth instance successfully.');
// The cancel() API can be called only after the authentication is started by start() of UserAuthInstance.
userAuthInstance.start();
console.info('auth start successfully.');
userAuthInstance.cancel();
console.info('auth cancel successfully.');
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`auth failed. Code is ${err?.code}, message is ${err?.message}`);
}
on('authTip')20+
on(type: 'authTip', callback: AuthTipCallback): void
Subscribes to authentication tip information. This API is used to obtain the component startup and exit messages and each authentication failure. This API uses an asynchronous callback to return the result.
NOTE
On PCs/2-in-1 devices, if an application initiates authentication in an application modal dialog (that is, a valid uiContext is passed when the user API parameter widgetParam is configured) and receives the authentication result, and if other windows need to be displayed, the application needs to obtain the flag message released by the component pop-up window and subscribe to the component release message (authTipInfo.tipCode = UserAuthTipCode.WIDGET_RELEASED) through the on('authTip') API.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.UserIAM.UserAuth.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Event type. The supported event is 'authTip'. This event is triggered when start() is called and authentication is initiated. |
| callback | AuthTipCallback | Yes | Callback used to return the intermediate authentication status. |
Error codes
For details about the error codes, see User Authentication Error Codes.
| ID | Error Message |
|---|---|
| 12500002 | General operation error. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { userAuth } from '@kit.UserAuthenticationKit';
try {
const rand = cryptoFramework.createRandom();
const len: number = 16;
let randData: Uint8Array | null = null;
let retryCount = 0;
while(retryCount < 3){
randData = rand?.generateRandomSync(len)?.data;
if(randData){
break;
}
retryCount++;
}
if(!randData){
return;
}
const authParam: userAuth.AuthParam = {
challenge: randData,
authType: [userAuth.UserAuthType.PIN],
authTrustLevel: userAuth.AuthTrustLevel.ATL3,
};
const widgetParam: userAuth.WidgetParam = {
title: 'Enter password',
};
const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
console.info('get userAuth instance successfully.');
// The intermediate authentication status is returned by onAuthTip only after the authentication is started by start() of UserAuthInstance.
userAuthInstance.on('authTip', (authTipInfo: userAuth.AuthTipInfo) => {
console.info('userAuthInstance callback.');
});
console.info('auth on successfully.');
userAuthInstance.start();
console.info('auth start successfully.');
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`auth failed. Code is ${err?.code}, message is ${err?.message}`);
}
off('authtip')20+
off(type: 'authTip', callback?: AuthTipCallback): void
Unsubscribes from the event for intermediate authentication status.
NOTE
The UserAuthInstance instance used to invoke this API must be the one used to subscribe to the event.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.UserIAM.UserAuth.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Event type. The supported event is 'authTip'. This API unsubscribes from the event triggered by on('authTip') after the start() call and the initiation of authentication. |
| callback | AuthTipCallback | No | Callback used to return the intermediate authentication status. If this parameter is not passed, the value passed when the on('authTip') API is called is used by default. |
Error codes
For details about the error codes, see User Authentication Error Codes.
| ID | Error Message |
|---|---|
| 12500002 | General operation error. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { userAuth } from '@kit.UserAuthenticationKit';
try {
const rand = cryptoFramework.createRandom();
const len: number = 16;
let randData: Uint8Array | null = null;
let retryCount = 0;
while(retryCount < 3){
randData = rand?.generateRandomSync(len)?.data;
if(randData){
break;
}
retryCount++;
}
if(!randData){
return;
}
const authParam: userAuth.AuthParam = {
challenge: randData,
authType: [userAuth.UserAuthType.PIN],
authTrustLevel: userAuth.AuthTrustLevel.ATL3,
};
const widgetParam: userAuth.WidgetParam = {
title: 'Enter password',
};
const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
console.info('get userAuth instance successfully.');
userAuthInstance.off('authTip', (authTipInfo: userAuth.AuthTipInfo) => {
console.info('userAuthInstance callback');
});
console.info('auth off successfully.');
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`auth failed. Code is ${err?.code}, message is ${err?.message}`);
}
userAuth.getUserAuthInstance10+
getUserAuthInstance(authParam: AuthParam, widgetParam: WidgetParam): UserAuthInstance
Obtains a UserAuthInstance instance for user authentication. The user authentication widget is also supported.
NOTE
Each UserAuthInstance can be used for authentication only once.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.UserIAM.UserAuth.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| authParam | AuthParam | Yes | User authentication parameters. |
| widgetParam | WidgetParam | Yes | Parameters on the user authentication page. |
Return value
| Type | Description |
|---|---|
| UserAuthInstance | UserAuthInstance instance that supports UI. |
Error codes
For details about the error codes, see Universal Error Codes and User Authentication Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
| 12500002 | General operation error. |
| 12500005 | The authentication type is not supported. |
| 12500006 | The authentication trust level is not supported. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { userAuth } from '@kit.UserAuthenticationKit';
try {
const rand = cryptoFramework.createRandom();
const len: number = 16;
let randData: Uint8Array | null = null;
let retryCount = 0;
while(retryCount < 3){
randData = rand?.generateRandomSync(len)?.data;
if(randData){
break;
}
retryCount++;
}
if(!randData){
return;
}
const authParam: userAuth.AuthParam = {
challenge: randData,
authType: [userAuth.UserAuthType.PIN],
authTrustLevel: userAuth.AuthTrustLevel.ATL3,
};
const widgetParam: userAuth.WidgetParam = {
title: 'Enter password',
};
let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
console.info('get userAuth instance successfully.');
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`auth failed. Code is ${err?.code}, message is ${err?.message}`);
}
AuthResultInfo(deprecated)
Represents the authentication result.
NOTE
This parameter is supported since API version 9 and deprecated since API version 11. Use UserAuthResult instead.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| result | number | No | No | Authentication result. |
| token | Uint8Array | No | Yes | Token that has passed the user identity authentication. |
| remainAttempts | number | No | Yes | Number of remaining authentication attempts. |
| lockoutDuration | number | No | Yes | Lock duration of the authentication operation, in ms. |
TipInfo(deprecated)
Represents the tip information displayed during the authentication, which is used to provide feedback during the authentication process.
NOTE
This API is supported since API version 9 and deprecated since API version 11. Use AuthTipInfo instead.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| module | number | No | No | ID of the module that sends the tip information. |
| tip | number | No | No | Tip to be given during the authentication process. |
EventInfo(deprecated)
type EventInfo = AuthResultInfo | TipInfo
Enumerates the authentication event information types.
It consists of the fields in Type in the following table.
NOTE
This parameter is supported since API version 9 and deprecated since API version 11. Use UserAuthResult instead.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Type | Description |
|---|---|
| AuthResultInfo | Authentication result. |
| TipInfo | Authentication tip information. |
AuthEventKey(deprecated)
type AuthEventKey = 'result' | 'tip'
Defines the keyword of the authentication event type. It is used as a parameter of on.
It consists of the fields in Type in the following table.
NOTE
This API is supported since API version 9 and deprecated since API version 11.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Type | Description |
|---|---|
| 'result' | If the first parameter of on is result, the callback returns the authentication result. |
| 'tip' | If the first parameter of on is tip, the callback returns the authentication tip information. |
AuthEvent(deprecated)
Provides an asynchronous callback to return the authentication event information.
NOTE
This API is supported since API version 9 and deprecated since API version 11. Use IAuthCallback instead.
callback(deprecated)
callback(result : EventInfo) : void
Called to return the authentication result or authentication tip information.
NOTE
This API is supported since API version 9 and deprecated since API version 11. Use onResult instead.
System capability: SystemCapability.UserIAM.UserAuth.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| result | EventInfo | Yes | Authentication result or tip information. |
Example
import { userAuth } from '@kit.UserAuthenticationKit';
let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
let authType = userAuth.UserAuthType.FACE;
let authTrustLevel = userAuth.AuthTrustLevel.ATL1;
// Obtain the authentication result via a callback.
try {
let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
auth.on('result', {
callback: (result: userAuth.AuthResultInfo) => {
console.info(`result: ${result.result}`);
}
} as userAuth.AuthEvent);
auth.start();
console.info('auth start successfully.');
} catch (error) {
console.error(`auth failed, error = ${error}`);
// do error.
}
// Obtain the authentication tip information via a callback.
try {
let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
auth.on('tip', {
callback : (result : userAuth.TipInfo) => {
switch (result.tip) {
case userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT:
// Do something.
break;
case userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK:
// Do something.
break;
default:
// do others.
}
}
} as userAuth.AuthEvent);
auth.start();
console.info('auth start successfully.');
} catch (error) {
console.error(`auth failed, error = ${error}`);
// do error.
}
AuthInstance(deprecated)
Implements user authentication.
NOTE
This API is supported since API version 9 and deprecated since API version 10. Use UserAuthInstance instead.
on(deprecated)
on : (name : AuthEventKey, callback : AuthEvent) => void
Subscribes to the user authentication events of the specified type.
NOTE
This API is supported since API version 9 and deprecated since API version 10. Use on('result') instead.
Use the AuthInstance instance obtained to call this API.
System capability: SystemCapability.UserIAM.UserAuth.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| name | AuthEventKey | Yes | Authentication event type. If the value is result, the callback returns the authentication result. If the value is tip, the callback returns the authentication tip information. |
| callback | AuthEvent | Yes | Callback used to return the authentication result or tip information. |
Error codes
For details about the error codes, see Universal Error Codes and User Authentication Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. |
| 12500002 | General operation error. |
Example
import { userAuth } from '@kit.UserAuthenticationKit';
let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
let authType = userAuth.UserAuthType.FACE;
let authTrustLevel = userAuth.AuthTrustLevel.ATL1;
try {
let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
// Subscribe to the authentication result.
auth.on('result', {
callback: (result: userAuth.AuthResultInfo) => {
console.info(`result: ${result.result}`);
}
});
// Subscribe to authentication tip information.
auth.on('tip', {
callback : (result : userAuth.TipInfo) => {
switch (result.tip) {
case userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT:
// Do something.
break;
case userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK:
// Do something.
break;
default:
// do others.
}
}
} as userAuth.AuthEvent);
auth.start();
console.info('auth start successfully.');
} catch (error) {
console.error(`auth failed, error = ${error}`);
// do error.
}
off(deprecated)
off : (name : AuthEventKey) => void
Unsubscribes from the user authentication events of the specified type.
NOTE
This API is supported since API version 9 and deprecated since API version 10. Use off('result') instead.
The AuthInstance instance used to invoke this API must be the one used to subscribe to the event.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Type | Mandatory | Description |
|---|---|---|---|
| name | AuthEventKey | Yes | Authentication event type. If the value is result, the authentication result is unsubscribed from. If the value is tip, the authentication tip information is unsubscribed from. |
Error codes
For details about the error codes, see Universal Error Codes and User Authentication Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. |
| 12500002 | General operation error. |
Example
import { userAuth } from '@kit.UserAuthenticationKit';
let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
let authType = userAuth.UserAuthType.FACE;
let authTrustLevel = userAuth.AuthTrustLevel.ATL1;
try {
let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
// Subscribe to the authentication result.
auth.on('result', {
callback: (result: userAuth.AuthResultInfo) => {
console.info(`result: ${result.result}`);
}
});
// Unsubscribe from the authentication result.
auth.off('result');
console.info('cancel subscribe authentication event successfully.');
} catch (error) {
console.error(`cancel subscribe authentication event failed, error = ${error}`);
// do error.
}
start(deprecated)
start : () => void
Starts authentication.
NOTE
This API is supported since API version 9 and deprecated since API version 10. Use start instead.
Use the AuthInstance instance obtained to call this API.
Required permissions: ohos.permission.ACCESS_BIOMETRIC
System capability: SystemCapability.UserIAM.UserAuth.Core
Error codes
For details about the error codes, see Universal Error Codes and User Authentication Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 12500001 | Authentication failed. |
| 12500002 | General operation error. |
| 12500003 | The operation is canceled. |
| 12500004 | The operation is time-out. |
| 12500005 | The authentication type is not supported. |
| 12500006 | The authentication trust level is not supported. |
| 12500007 | The authentication task is busy. |
| 12500009 | The authenticator is locked. |
| 12500010 | The type of credential has not been enrolled. |
Example
import { userAuth } from '@kit.UserAuthenticationKit';
let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
let authType = userAuth.UserAuthType.FACE;
let authTrustLevel = userAuth.AuthTrustLevel.ATL1;
try {
let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
auth.start();
console.info('auth start successfully.');
} catch (error) {
console.error(`auth failed, error = ${error}`);
}
cancel(deprecated)
cancel : () => void
Cancels this authentication.
NOTE
This API is supported since API version 9 and deprecated since API version 10. Use cancel instead.
Use the AuthInstance instance obtained to call this API. The AuthInstance instance must be the instance being authenticated.
Required permissions: ohos.permission.ACCESS_BIOMETRIC
System capability: SystemCapability.UserIAM.UserAuth.Core
Error codes
For details about the error codes, see Universal Error Codes and User Authentication Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 12500002 | General operation error. |
Example
import { userAuth } from '@kit.UserAuthenticationKit';
let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
let authType = userAuth.UserAuthType.FACE;
let authTrustLevel = userAuth.AuthTrustLevel.ATL1;
try {
let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
auth.cancel();
console.info('cancel auth successfully.');
} catch (error) {
console.error(`auth failed, error = ${error}`);
}
userAuth.getAuthInstance(deprecated)
getAuthInstance(challenge : Uint8Array, authType : UserAuthType, authTrustLevel : AuthTrustLevel): AuthInstance
Obtains an AuthInstance instance for user authentication.
NOTE
This API is supported since API version 9 and deprecated since API version 10. Use getUserAuthInstance instead.
An AuthInstance instance can be used for authentication only once.
System capability: SystemCapability.UserIAM.UserAuth.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| challenge | Uint8Array | Yes | Challenge value. It cannot exceed 32 bytes and can be passed in Uint8Array([]) format. |
| authType | UserAuthType | Yes | Authentication type. Currently, FACE and FINGERPRINT are supported. |
| authTrustLevel | AuthTrustLevel | Yes | Authentication trust level. |
Return value
| Type | Description |
|---|---|
| AuthInstance | AuthInstance instance obtained. |
Error codes
For details about the error codes, see Universal Error Codes and User Authentication Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. |
| 12500002 | General operation error. |
| 12500005 | The authentication type is not supported. |
| 12500006 | The authentication trust level is not supported. |
Example
import { userAuth } from '@kit.UserAuthenticationKit';
let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
let authType = userAuth.UserAuthType.FACE;
let authTrustLevel = userAuth.AuthTrustLevel.ATL1;
try {
let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
console.info('get auth instance successfully.');
} catch (error) {
console.error(`get auth instance failed, error = ${error}`);
}
userAuth.getAvailableStatus9+
getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel): void
Checks whether the specified authentication capability is supported.
Required permissions: ohos.permission.ACCESS_BIOMETRIC
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.UserIAM.UserAuth.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| authType | UserAuthType | Yes | Authentication type. PIN is supported since API version 11. |
| authTrustLevel | AuthTrustLevel | Yes | Authentication trust level. |
The mechanism for returning the error code is as follows:
Error code 12500005 is returned if the authentication executor is not registered and the specified authentication capability is not supported.
Error code 12500006 is returned if the authentication executor has been registered, the authentication functionality is not disabled, but the authentication trust level is lower than that specified by the service.
Error code 12500010 is returned if the authentication executor has been registered, the authentication functionality is not disabled, but the user has not enrolled credential.
Error code 12500013 is returned if the authentication executor has been registered, the authentication functionality is not disabled, but the password has expired.
NOTE
If getAvailableStatus is called to check whether lock screen password authentication at ATL4 is supported for a user who has enrolled a 4-digit PIN as the lock screen password (the authentication trust level is ATL3), error code 12500010 will be returned.
Error codes
For details about the error codes, see Universal Error Codes and User Authentication Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. |
| 12500002 | General operation error. |
| 12500005 | The authentication type is not supported. |
| 12500006 | The authentication trust level is not supported. |
| 12500010 | The type of credential has not been enrolled. |
| 12500013 | Operation failed because of PIN expired. |
Example
import { userAuth } from '@kit.UserAuthenticationKit';
try {
userAuth.getAvailableStatus(userAuth.UserAuthType.FACE, userAuth.AuthTrustLevel.ATL3);
console.info('current auth trust level is supported');
} catch (error) {
console.error(`current auth trust level is not supported, error = ${error}`);
}
UserAuthResultCode9+
Enumerates the authentication result codes.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Value | Description |
|---|---|---|
| SUCCESS | 12500000 | The operation is successful. Atomic service API: This API can be used in atomic services since API version 12. |
| FAIL | 12500001 | The authentication failed. Atomic service API: This API can be used in atomic services since API version 12. |
| GENERAL_ERROR | 12500002 | A general operation error occurred. Atomic service API: This API can be used in atomic services since API version 12. |
| CANCELED | 12500003 | The authentication is canceled. Atomic service API: This API can be used in atomic services since API version 12. |
| TIMEOUT | 12500004 | The authentication has timed out. Atomic service API: This API can be used in atomic services since API version 12. |
| TYPE_NOT_SUPPORT | 12500005 | The authentication type is not supported. Atomic service API: This API can be used in atomic services since API version 12. |
| TRUST_LEVEL_NOT_SUPPORT | 12500006 | The authentication trust level is not supported. Atomic service API: This API can be used in atomic services since API version 12. |
| BUSY | 12500007 | The system does not respond. Atomic service API: This API can be used in atomic services since API version 12. |
| INVALID_PARAMETERS20+ | 12500008 | Parameter verification failed. Atomic service API: This API can be used in atomic services since API version 20. |
| LOCKED | 12500009 | The authentication executor is locked. Atomic service API: This API can be used in atomic services since API version 12. |
| NOT_ENROLLED | 12500010 | The user has not enrolled the specified system identity authentication credential. Atomic service API: This API can be used in atomic services since API version 12. |
| CANCELED_FROM_WIDGET10+ | 12500011 | The user cancels the system authentication and selects a custom authentication of the application. The caller needs to launch the custom authentication page. Atomic service API: This API can be used in atomic services since API version 12. |
| PIN_EXPIRED12+ | 12500013 | The authentication failed because the lock screen password has expired. Atomic service API: This API can be used in atomic services since API version 12. |
UserAuth(deprecated)
Provides APIs for managing the UserAuth object.
constructor(deprecated)
constructor()
A constructor used to create a UserAuth instance.
NOTE
This API is supported since API version 8 and deprecated since API version 9. Use getAuthInstance instead.
System capability: SystemCapability.UserIAM.UserAuth.Core
Example
import { userAuth } from '@kit.UserAuthenticationKit';
let auth = new userAuth.UserAuth();
getVersion(deprecated)
getVersion() : number
Obtains the version of this authenticator.
NOTE
This API is supported since API version 8 and deprecated since API version 9.
Required permissions: ohos.permission.ACCESS_BIOMETRIC
System capability: SystemCapability.UserIAM.UserAuth.Core
Return value
| Type | Description |
|---|---|
| number | Authenticator version obtained. |
Example
import { userAuth } from '@kit.UserAuthenticationKit';
let auth = new userAuth.UserAuth();
let version = auth.getVersion();
console.info(`auth version = ${version}`);
getAvailableStatus(deprecated)
getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel) : number
Checks whether the specified authentication capability is supported.
NOTE
This API is supported since API version 8 and deprecated since API version 9. Use getAvailableStatus instead.
Required permissions: ohos.permission.ACCESS_BIOMETRIC
System capability: SystemCapability.UserIAM.UserAuth.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| authType | UserAuthType | Yes | Authentication type. Currently, FACE and FINGERPRINT are supported. |
| authTrustLevel | AuthTrustLevel | Yes | Authentication trust level. |
Return value
| Type | Description |
|---|---|
| number | Query result. If the authentication capability is supported, SUCCESS is returned. Otherwise, a ResultCode is returned. |
Example
import { userAuth } from '@kit.UserAuthenticationKit';
let auth = new userAuth.UserAuth();
let checkCode = auth.getAvailableStatus(userAuth.UserAuthType.FACE, userAuth.AuthTrustLevel.ATL1);
if (checkCode == userAuth.ResultCode.SUCCESS) {
console.info('check auth support successfully.');
} else {
console.error(`check auth support failed, code = ${checkCode}`);
}
auth(deprecated)
auth(challenge: Uint8Array, authType: UserAuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array
Starts user authentication. This API uses a callback to return the result.
NOTE
This API is supported since API version 8 and deprecated since API version 9. Use start instead.
Required permissions: ohos.permission.ACCESS_BIOMETRIC
System capability: SystemCapability.UserIAM.UserAuth.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| challenge | Uint8Array | Yes | Challenge value, which can be passed in Uint8Array([]) format. |
| authType | UserAuthType | Yes | Authentication type. Currently, FACE and FINGERPRINT are supported. |
| authTrustLevel | AuthTrustLevel | Yes | Authentication trust level. |
| callback | IUserAuthCallback | Yes | Callback used to return the result. |
Return value
| Type | Description |
|---|---|
| Uint8Array | Context ID, which is used as the input parameter of cancelAuth. |
Example
import { userAuth } from '@kit.UserAuthenticationKit';
let auth = new userAuth.UserAuth();
let challenge = new Uint8Array([]);
auth.auth(challenge, userAuth.UserAuthType.FACE, userAuth.AuthTrustLevel.ATL1, {
onResult: (result, extraInfo) => {
try {
console.info(`auth onResult result = ${result}`);
if (result == userAuth.ResultCode.SUCCESS) {
// Add the logic to be executed when the authentication is successful.
} else {
// Add the logic to be executed when the authentication fails.
}
} catch (error) {
console.error(`auth onResult failed, error = ${error}`);
}
}
});
cancelAuth(deprecated)
cancelAuth(contextID : Uint8Array) : number
Cancels the authentication based on the context ID.
NOTE
This API is supported since API version 8 and deprecated since API version 9. Use cancel instead.
Required permissions: ohos.permission.ACCESS_BIOMETRIC
System capability: SystemCapability.UserIAM.UserAuth.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| contextID | Uint8Array | Yes | Context ID, which is obtained by auth. |
Return value
| Type | Description |
|---|---|
| number | Returns SUCCESS if the cancellation is successful. Returns a ResultCode otherwise. |
Example
import { userAuth } from '@kit.UserAuthenticationKit';
// contextId can be obtained via auth(). In this example, it is defined here.
let contextId = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]);
let auth = new userAuth.UserAuth();
let cancelCode = auth.cancelAuth(contextId);
if (cancelCode == userAuth.ResultCode.SUCCESS) {
console.info('cancel auth successfully.');
} else {
console.error('cancel auth failed.');
}
IUserAuthCallback(deprecated)
Provides callbacks to return the authentication result.
NOTE
This API is supported since API version 8 and deprecated since API version 9. Use AuthEvent instead.
onResult(deprecated)
onResult: (result : number, extraInfo : AuthResult) => void
Called to return the authentication result.
NOTE
This API is supported since API version 8 and deprecated since API version 9. Use callback instead.
System capability: SystemCapability.UserIAM.UserAuth.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| result | number | Yes | Authentication result. For details, see ResultCode. |
| extraInfo | AuthResult | Yes | Extended information, which varies depending on the authentication result. If the authentication is successful, the user authentication token will be returned in extraInfo. If the authentication fails, the remaining number of authentication times will be returned in extraInfo. If the authentication executor is locked, the freeze time will be returned in extraInfo. |
Example
import { userAuth } from '@kit.UserAuthenticationKit';
let auth = new userAuth.UserAuth();
let challenge = new Uint8Array([]);
auth.auth(challenge, userAuth.UserAuthType.FACE, userAuth.AuthTrustLevel.ATL1, {
onResult: (result, extraInfo) => {
try {
console.info(`auth onResult result = ${result}`);
if (result == userAuth.ResultCode.SUCCESS) {
// Add the logic to be executed when the authentication is successful.
} else {
// Add the logic to be executed when the authentication fails.
}
} catch (error) {
console.error(`auth onResult failed, error = ${error}`);
}
}
});
onAcquireInfo(deprecated)
onAcquireInfo ?: (module : number, acquire : number, extraInfo : any) => void
Called to acquire authentication tip information. This API is optional.
NOTE
This API is supported since API version 8 and deprecated since API version 9. Use callback instead.
System capability: SystemCapability.UserIAM.UserAuth.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| module | number | Yes | ID of the module that sends the tip information. |
| acquire | number | Yes | Authentication tip information. |
| extraInfo | any | Yes | Reserved field. |
Example
import { userAuth } from '@kit.UserAuthenticationKit';
let auth = new userAuth.UserAuth();
let challenge = new Uint8Array([]);
auth.auth(challenge, userAuth.UserAuthType.FACE, userAuth.AuthTrustLevel.ATL1, {
onResult: (result, extraInfo) => {
try {
console.info(`auth onResult result = ${result}`);
if (result == userAuth.ResultCode.SUCCESS) {
// Add the logic to be executed when the authentication is successful.
} else {
// Add the logic to be executed when the authentication fails.
}
} catch (error) {
console.error(`auth onResult failed, error = ${error}`);
}
},
onAcquireInfo: (module, acquire, extraInfo : userAuth.AuthResult) => {
try {
console.info('auth onAcquireInfo successfully.');
} catch (error) {
console.error(`auth onAcquireInfo failed, error = ${error}`);
}
}
});
AuthResult(deprecated)
Represents the authentication result object.
NOTE
This API is supported since API version 8 and deprecated since API version 9. Use AuthResultInfo instead.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| token | Uint8Array | No | Yes | Authentication token information. |
| remainTimes | number | No | Yes | Number of remaining authentication operations. |
| freezingTime | number | No | Yes | Time for which the authentication operation is frozen. The unit is milliseconds. |
ResultCode(deprecated)
Enumerates the authentication result codes.
NOTE
This API is supported since API version 8 and deprecated since API version 9. Use UserAuthResultCode instead.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Value | Description |
|---|---|---|
| SUCCESS | 0 | The operation is successful. |
| FAIL | 1 | The authentication failed. |
| GENERAL_ERROR | 2 | A general operation error occurred. |
| CANCELED | 3 | The authentication is canceled. |
| TIMEOUT | 4 | The authentication timed out. |
| TYPE_NOT_SUPPORT | 5 | The authentication type is not supported. |
| TRUST_LEVEL_NOT_SUPPORT | 6 | The authentication trust level is not supported. |
| BUSY | 7 | Indicates the busy state. |
| INVALID_PARAMETERS | 8 | Invalid parameters are detected. |
| LOCKED | 9 | The authentication executor is locked. |
| NOT_ENROLLED | 10 | The user has not enrolled the authentication information. |
FaceTips(deprecated)
Enumerates the tip codes used during the facial authentication process.
NOTE
This API is supported since API version 8 and deprecated since API version 11.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Value | Description |
|---|---|---|
| FACE_AUTH_TIP_TOO_BRIGHT | 1 | The obtained facial image is too bright due to high illumination. |
| FACE_AUTH_TIP_TOO_DARK | 2 | The obtained facial image is too dark due to low illumination. |
| FACE_AUTH_TIP_TOO_CLOSE | 3 | The face is too close to the device. |
| FACE_AUTH_TIP_TOO_FAR | 4 | The face is too far away from the device. |
| FACE_AUTH_TIP_TOO_HIGH | 5 | Only the upper part of the face is captured because the device is angled too high. |
| FACE_AUTH_TIP_TOO_LOW | 6 | Only the lower part of the face is captured because the device is angled too low. |
| FACE_AUTH_TIP_TOO_RIGHT | 7 | Only the right part of the face is captured because the device is deviated to the right. |
| FACE_AUTH_TIP_TOO_LEFT | 8 | Only the left part of the face is captured because the device is deviated to the left. |
| FACE_AUTH_TIP_TOO_MUCH_MOTION | 9 | The face moves too fast during facial information collection. |
| FACE_AUTH_TIP_POOR_GAZE | 10 | The face is not facing the camera. |
| FACE_AUTH_TIP_NOT_DETECTED | 11 | No face is detected. |
FingerprintTips(deprecated)
Enumerates the tip codes used during the fingerprint authentication process.
NOTE
This API is supported since API version 8 and deprecated since API version 11.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Value | Description |
|---|---|---|
| FINGERPRINT_AUTH_TIP_GOOD | 0 | The obtained fingerprint image is in good condition. |
| FINGERPRINT_AUTH_TIP_DIRTY | 1 | Large fingerprint image noise is detected due to suspicious or detected dirt on the sensor. |
| FINGERPRINT_AUTH_TIP_INSUFFICIENT | 2 | The noise of the fingerprint image is too large to be processed. |
| FINGERPRINT_AUTH_TIP_PARTIAL | 3 | Incomplete fingerprint image is detected. |
| FINGERPRINT_AUTH_TIP_TOO_FAST | 4 | The fingerprint image is incomplete due to fast movement. |
| FINGERPRINT_AUTH_TIP_TOO_SLOW | 5 | Failed to obtain the fingerprint image because the finger seldom moves. |
UserAuthType8+
Enumerates the identity authentication types.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Value | Description |
|---|---|---|
| PIN10+ | 1 | PIN authentication. |
| FACE | 2 | Facial authentication. |
| FINGERPRINT | 4 | Fingerprint authentication. |
AuthTrustLevel8+
Enumerates the trust levels of the authentication result.
For typical use cases, see Principles for Classifying Biometric Authentication Trust Levels.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Value | Description |
|---|---|---|
| ATL1 | 10000 | Authentication trust level 1. The authentication of this level can identify individual users and provides limited liveness detection capabilities. It is applicable to scenarios such as service risk control and access to common personal data. |
| ATL2 | 20000 | Authentication trust level 2. The authentication of this level can accurately identify individual users and provides regular liveness detection capabilities. It is applicable to scenarios such as device unlocking and application login. |
| ATL3 | 30000 | Authentication trust level 3. The authentication of this level can accurately identify individual users and provides strong liveness detection capabilities. It is applicable to scenarios such as device unlocking. |
| ATL4 | 40000 | Authentication trust level 4. The authentication of this level can accurately identify individual users and provides powerful liveness detection capabilities. It is applicable to scenarios such as small-amount payment. |
SecureLevel(deprecated)
type SecureLevel = string
Enumerates the authentication security levels.
NOTE
This API is supported since API version 6 and deprecated since API version 8. Use AuthTrustLevel instead.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Type | Description |
|---|---|
| string | String type. The authentication security level can be 'S1' | 'S2'|'S3'|'S4'. - S1: authentication trust level 1. The authentication of this level can identify individual users and provides limited liveness detection capabilities. It is usually used in service risk control and query of general personal data. - S2: authentication trust level 2. The authentication of this level can accurately identify individual users and provides regular liveness detection capabilities. It is usually used in scenarios such as application logins and keeping the unlocking state of a device. - S3: authentication trust level 3. The authentication of this level can accurately identify individual users and provides strong liveness detection capabilities. It is usually used in scenarios such as unlocking a device. - S4: authentication trust level 4. The authentication of this level can accurately identify individual users and provides powerful liveness detection capabilities. It is usually used in scenarios such as small-amount payment. |
AuthType(deprecated)
type AuthType = string
Enumerates the authentication types.
NOTE
This API is supported since API version 6 and deprecated since API version 8. Use UserAuthType instead.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Type | Description |
|---|---|
| string | Authentication mode, which can be any of the following: 'ALL'|'FACE_ONLY'. - ALL: reserved and not supported by the current version. - FACE_ONLY: facial authentication. |
userAuth.getAuthenticator(deprecated)
getAuthenticator(): Authenticator
Obtains an Authenticator instance for user authentication.
NOTE
This API is supported since API version 6 and deprecated since API version 8. Use getAuthInstance instead.
System capability: SystemCapability.UserIAM.UserAuth.Core
Return value
| Type | Description |
|---|---|
| Authenticator | Authenticator instance obtained. |
Example
import { userAuth } from '@kit.UserAuthenticationKit';
let authenticator = userAuth.getAuthenticator();
Authenticator(deprecated)
Provides APIs for managing the Authenticator object.
NOTE
This API is supported since API version 6 and deprecated since API version 8. Use AuthInstance instead.
execute(deprecated)
execute(type: AuthType, level: SecureLevel, callback: AsyncCallback<number>): void
Starts user authentication. This API uses an asynchronous callback to return the result.
NOTE
This API is supported since API version 6 and deprecated since API version 8. Use start instead.
Required permissions: ohos.permission.ACCESS_BIOMETRIC
System capability: SystemCapability.UserIAM.UserAuth.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | AuthType | Yes | Authentication type. Currently, only FACE_ONLY is supported. ALL is reserved and not supported by the current version. |
| level | SecureLevel | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest). Devices capable of 3D facial recognition support S3 and lower-level authentication. Devices capable of 2D facial recognition support S2 and lower-level authentication. |
| callback | AsyncCallback<number> | Yes | Callback used to return the result. number indicates the AuthenticationResult. |
Example
import { userAuth } from '@kit.UserAuthenticationKit';
let authenticator = userAuth.getAuthenticator();
authenticator.execute('FACE_ONLY', 'S2', (error, code)=>{
if (code === userAuth.ResultCode.SUCCESS) {
console.info('auth successfully.');
return;
}
console.error(`auth failed, code = ${code}`);
});
execute(deprecated)
execute(type : AuthType, level : SecureLevel): Promise<number>
Starts user authentication. This API uses a promise to return the result.
NOTE
This API is supported since API version 6 and deprecated since API version 8. Use start instead.
Required permissions: ohos.permission.ACCESS_BIOMETRIC
System capability: SystemCapability.UserIAM.UserAuth.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | AuthType | Yes | Authentication type. Currently, only FACE_ONLY is supported. ALL is reserved and not supported by the current version. |
| level | SecureLevel | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest). Devices capable of 3D facial recognition support S3 and lower-level authentication. Devices capable of 2D facial recognition support S2 and lower-level authentication. |
Return value
| Type | Description |
|---|---|
| Promise<number> | Promise used to return the authentication result, which is a number. For details, see AuthenticationResult. |
Example
import { userAuth } from '@kit.UserAuthenticationKit';
try {
let authenticator = userAuth.getAuthenticator();
authenticator.execute('FACE_ONLY', 'S2').then((code)=>{
console.info('auth successfully.');
})
} catch (error) {
console.error(`auth failed, code = ${error}`);
}
AuthenticationResult(deprecated)
Enumerates the authentication results.
NOTE
This API is supported since API version 6 and deprecated since API version 8. Use UserAuthResultCode instead.
System capability: SystemCapability.UserIAM.UserAuth.Core
| Name | Value | Description |
|---|---|---|
| NO_SUPPORT | -1 | The device does not support the current authentication mode. |
| SUCCESS | 0 | The authentication is successful. |
| COMPARE_FAILURE | 1 | The feature comparison failed. |
| CANCELED | 2 | The authentication was canceled by the user. |
| TIMEOUT | 3 | The authentication has timed out. |
| CAMERA_FAIL | 4 | The camera failed to start. |
| BUSY | 5 | The authentication service is not available. Try again later. |
| INVALID_PARAMETERS | 6 | The authentication parameters are invalid. |
| LOCKED | 7 | The user account is locked because the number of authentication failures has reached the threshold. |
| NOT_ENROLLED | 8 | No authentication credential is registered. |
| GENERAL_ERROR | 100 | Other errors. |