harmony 鸿蒙@ohos.userIAM.userAuth (User Authentication)

2022-08-09 浏览 (1281)

@ohos.userIAM.userAuth (User Authentication)

The userIAM.userAuth module provides user authentication capabilities in identity authentication scenarios, such as device unlocking, payment, and app 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 userIAM_userAuth from '@ohos.userIAM.userAuth';

WindowModeType10+

Enumerates the window types of the authentication widget.

System capability: SystemCapability.UserIAM.UserAuth.Core

System API: This is a system API.

NameValueDescription
DIALOG_BOX1Dialog box.
FULLSCREEN2Full screen.

AuthParam10+

Defines the user authentication parameters.

System capability: SystemCapability.UserIAM.UserAuth.Core

NameTypeMandatoryDescription
challengeUint8ArrayYesChallenge value, which is used to prevent replay attacks. It cannot exceed 32 bytes and can be passed in Uint8Array([]) format.
authTypeUserAuthType[]YesAuthentication type list, which specifies the types of authentication provided on the user authentication page.
authTrustLevelAuthTrustLevelYesAuthentication trust level.

WidgetParam10+

Represents the information presented on the user authentication page.

System capability: SystemCapability.UserIAM.UserAuth.Core

NameTypeMandatoryDescription
titlestringYesTitle of the user authentication page. It cannot exceed 500 characters.
navigationButtonTextstringNoText on the navigation button. It cannot exceed 60 characters. This parameter is valid only in fingerprint or facial authentication only.
windowModeWindowModeTypeNoDisplay format of the user authentication page. The default value is WindowModeType.DIALOG_BOX.
System API: This is a system API.

UserAuthResult10+

Defines the user authentication result. If the authentication is successful, the authentication type and information about the token that has passed the authentication are returned.

System capability: SystemCapability.UserIAM.UserAuth.Core

NameTypeMandatoryDescription
resultnumberYesUser authentication result. If the operation is successful, 0 is returned. If the operation fails, an error code is returned. For details about the error codes, see User Authentication Error Codes.
tokenUint8ArrayNoToken that has passed the authentication.
authTypeUserAuthTypeNoType of the authentication.

IAuthCallback10+

Provides callbacks to return the authentication result.

onResult10+

onResult(result: UserAuthResult): void

Called to return the authentication result.

System capability: SystemCapability.UserIAM.UserAuth.Core

Parameters

NameTypeMandatoryDescription
resultUserAuthResultYesAuthentication result.

Example

import userAuth from '@ohos.userIAM.userAuth';

const authParam : userAuth.AuthParam = {
  challenge: new Uint8Array([49, 49, 49, 49, 49, 49]),
  authType: [userAuth.UserAuthType.PIN],
  authTrustLevel: userAuth.AuthTrustLevel.ATL1,
};
const widgetParam :userAuth.WidgetParam = {
  title:'Enter password',
};
try {
  let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
  console.log('get userAuth instance success');
  userAuthInstance.on('result', {
    onResult (result) {
      console.log('userAuthInstance callback result = ' + JSON.stringify(result));
    }
  });
  console.log('auth on success');
} catch (error) {
  console.log('auth catch error: ' + JSON.stringify(error));
}

UserAuthInstance10+

Provides APIs for user authentication. The user authentication widget is supported. Before using the APIs, you need to obtain a UserAuthInstance instance by using getUserAuthInstance.

on10+

on(type: 'result', callback: IAuthCallback): void

Subscribes to the user authentication result.

System capability: SystemCapability.UserIAM.UserAuth.Core

Parameters

NameTypeMandatoryDescription
type'result'YesEvent type. The value is result, which indicates the authentication result.
callbackIAuthCallbackYesCallback invoked to return the user authentication result.

Error codes

For details about the error codes, see User Authentication Error Codes.

IDError Message
401Incorrect parameters.
12500002General operation error.

Example

import userAuth from '@ohos.userIAM.userAuth';

const authParam : userAuth.AuthParam = {
  challenge: new Uint8Array([49, 49, 49, 49, 49, 49]),
  authType: [userAuth.UserAuthType.PIN],
  authTrustLevel: userAuth.AuthTrustLevel.ATL1,
};
const widgetParam :userAuth.WidgetParam = {
  title:'Enter password',
};
try {
  let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
  console.log('get userAuth instance success');
  userAuthInstance.on('result', {
    onResult (result) {
      console.log('userAuthInstance callback result = ' + JSON.stringify(result));
    }
  });
  console.log('auth on success');
} catch (error) {
  console.log('auth catch error: ' + JSON.stringify(error));
}

off10+

off(type: 'result', callback?: IAuthCallback): void

Unsubscribes from the user authentication result.

NOTE

You need to use the UserAuthInstance instance that has successfully subscribed to the event to call this API.

System capability: SystemCapability.UserIAM.UserAuth.Core

Parameters

NameTypeMandatoryDescription
type'result'YesEvent type. The value is result, which indicates the authentication result.
callbackIAuthCallbackNoCallback for the user authentication result.

Error codes

For details about the error codes, see User Authentication Error Codes.

IDError Message
401Incorrect parameters.
12500002General operation error.

Example

import userAuth from '@ohos.userIAM.userAuth';

const authParam : userAuth.AuthParam = {
  challenge: new Uint8Array([49, 49, 49, 49, 49, 49]),
  authType: [userAuth.UserAuthType.PIN],
  authTrustLevel: userAuth.AuthTrustLevel.ATL1,
};
const widgetParam :userAuth.WidgetParam = {
  title:'Enter password',
};
try {
  let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
  console.log('get userAuth instance success');
  userAuthInstance.off('result', {
    onResult (result) {
      console.log('auth off result: ' + JSON.stringify(result));
    }
  });
  console.log('auth off success');
} catch (error) {
  console.log('auth catch error: ' + JSON.stringify(error));
}

start10+

start(): void

Starts authentication.

Required permissions: ohos.permission.ACCESS_BIOMETRIC

System capability: SystemCapability.UserIAM.UserAuth.Core

Error codes

For details about the error codes, see User Authentication Error Codes.

IDError Message
201Permission verification failed.
401Incorrect parameters.
12500001Authentication failed.
12500002General operation error.
12500003The operation is canceled.
12500004The operation is time-out.
12500005The authentication type is not supported.
12500006The authentication trust level is not supported.
12500007The authentication task is busy.
12500009The authenticator is locked.
12500010The type of credential has not been enrolled.
12500011The authentication is canceled from widget's navigation button.

Example

import userAuth from '@ohos.userIAM.userAuth';

const authParam : userAuth.AuthParam = {
  challenge: new Uint8Array([49, 49, 49, 49, 49, 49]),
  authType: [userAuth.UserAuthType.PIN],
  authTrustLevel: userAuth.AuthTrustLevel.ATL1,
};
const widgetParam :userAuth.WidgetParam = {
  title:'Enter password',
};
try {
  let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
  console.log('get userAuth instance success');
  userAuthInstance.start();
  console.log('auth start success');
} catch (error) {
  console.log('auth catch error: ' + JSON.stringify(error));
}

cancel10+

cancel(): void

Cancels this authentication.

NOTE
UserAuthInstance must be the instance being authenticated.

Required permissions: ohos.permission.ACCESS_BIOMETRIC

System capability: SystemCapability.UserIAM.UserAuth.Core

Error codes

IDError Message
201Permission verification failed.
401Incorrect parameters.
12500002General operation error.

Example

import userAuth from '@ohos.userIAM.userAuth';

const authParam : userAuth.AuthParam = {
  challenge: new Uint8Array([49, 49, 49, 49, 49, 49]),
  authType: [userAuth.UserAuthType.PIN],
  authTrustLevel: userAuth.AuthTrustLevel.ATL1,
};
const widgetParam :userAuth.WidgetParam = {
  title:'Enter password',
};
try {
  let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
  console.log('get userAuth instance success');
  userAuthInstance.cancel();
  console.log('auth cancel success');
} catch (error) {
  console.log('auth catch error: ' + JSON.stringify(error));
}

getUserAuthInstance10+

getUserAuthInstance(authParam: AuthParam, widgetParam: WidgetParam): UserAuthInstance

Obtains a UserAuthInstance instance for user authentication. The user authentication widget is supported.

NOTE

A UserAuthInstance instance can be used for an authentication only once.

System capability: SystemCapability.UserIAM.UserAuth.Core

Parameters

NameTypeMandatoryDescription
authParamAuthParamYesUser authentication parameters.
widgetParamWidgetParamYesParameters on the user authentication page.

Return value

TypeDescription
UserAuthInstanceUserAuthInstance instance that supports UI.

Error codes

For details about the error codes, see User Authentication Error Codes.

IDError Message
401Incorrect parameters.
12500002General operation error.
12500005The authentication type is not supported.
12500006The authentication trust level is not supported.

Example

import userAuth from '@ohos.userIAM.userAuth';

const authParam : userAuth.AuthParam = {
  challenge: new Uint8Array([49, 49, 49, 49, 49, 49]),
  authType: [userAuth.UserAuthType.PIN],
  authTrustLevel: userAuth.AuthTrustLevel.ATL1,
};
const widgetParam :userAuth.WidgetParam = {
  title:'Enter password',
};
try {
  let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
  console.log('get userAuth instance success');
} catch (error) {
  console.log('auth catch error: ' + JSON.stringify(error));
}

NoticeType10+

Defines the type of the user authentication notification.

System capability: SystemCapability.UserIAM.UserAuth.Core

System API: This is a system API.

NameValueDescription
WIDGET_NOTICE1Notification from the user authentication widget.

sendNotice10+

sendNotice(noticeType: NoticeType, eventData: string): void

Sends a notification from the user authentication widget.

Required permissions: ohos.permission.SUPPORT_USER_AUTH

System capability: SystemCapability.UserIAM.UserAuth.Core

System API: This is a system API.

Parameters

NameTypeMandatoryDescription
noticeTypeNoticeTypeYesNotification type.
eventDatastringYesEvent data.

Error codes

For details about the error codes, see User Authentication Error Codes.

IDError Message
201Permission verification failed.
202The caller is not a system application.
401Incorrect parameters.
12500002General operation error.

Example

import userAuth from '@ohos.userIAM.userAuth';

interface  EventData {
  widgetContextId: number;
  event: string;
  version: string;
  payload: PayLoad;
}
interface PayLoad {
  type: Object[];
}
try {
  const eventData : EventData = {
    widgetContextId: 123456,
    event: 'EVENT_AUTH_TYPE_READY',
    version: '1',
    payload: {
      type: ['pin']
    } as PayLoad,
  };
  const jsonEventData = JSON.stringify(eventData);
  let noticeType = userAuth.NoticeType.WIDGET_NOTICE;
  userAuth.sendNotice(noticeType, jsonEventData);
  console.log('sendNotice success');
} catch (error) {
  console.log('sendNotice catch error: ' + JSON.stringify(error));
}

UserAuthWidgetMgr10+

Provides APIs for managing the user authentication widget. You can use the APIs to register the user authentication widget with UserAuthWidgetMgr for management and scheduling.

on10+

on(type: 'command', callback: IAuthWidgetCallback): void

Subscribes to commands from the user authentication framework.

System capability: SystemCapability.UserIAM.UserAuth.Core

System API: This is a system API.

Parameters

NameTypeMandatoryDescription
type'command'YesEvent type. The vlaue is command, which indicates the command sent from the user authentication framework to the user authentication widget.
callbackIAuthWidgetCallbackYesCallback invoked to send the command from the user authentication framework to the user authentication widget.

Error codes

For details about the error codes, see User Authentication Error Codes.

IDError Message
401Incorrect parameters.
12500002General operation error.

Example

import userAuth from '@ohos.userIAM.userAuth';

const userAuthWidgetMgrVersion = 1;
try {
  let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion);
  console.log('get userAuthWidgetMgr instance success');
  userAuthWidgetMgr.on('command', {
    sendCommand(cmdData) {
      console.log('The cmdData is ' + cmdData);
    }
  })
  console.log('subscribe authentication event success');
} catch (error) {
  console.log('userAuth widgetMgr catch error: ' + JSON.stringify(error));
}

off10+

off(type: 'command', callback?: IAuthWidgetCallback): void

Unsubscribes from commands sent from the user authentication framework.

System capability: SystemCapability.UserIAM.UserAuth.Core

System API: This is a system API.

Parameters

NameTypeMandatoryDescription
type'command'YesEvent type. The value is command, which indicates the command sent from the user authentication framework to the user authentication widget.
callbackIAuthWidgetCallbackNoCallback for the command sent from the user authentication framework to the user authentication widget.

Error codes

For details about the error codes, see User Authentication Error Codes.

IDError Message
401Incorrect parameters.
12500002General operation error.

Example

import userAuth from '@ohos.userIAM.userAuth';

const userAuthWidgetMgrVersion = 1;
try {
  let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion);
  console.log('get userAuthWidgetMgr instance success');
  userAuthWidgetMgr.off('command', {
    sendCommand(cmdData) {
      console.log('The cmdData is ' + cmdData);
    }
  })
  console.log('cancel subscribe authentication event success');
} catch (error) {
  console.log('userAuth widgetMgr catch error: ' + JSON.stringify(error));
}

getUserAuthWidgetMgr10+

getUserAuthWidgetMgr(version: number): UserAuthWidgetMgr

Obtains a UserAuthWidgetMgr instance for user authentication.

NOTE
A UserAuthInstance instance can be used for an authentication only once.

Required permissions: ohos.permission.SUPPORT_USER_AUTH

System capability: SystemCapability.UserIAM.UserAuth.Core

System API: This is a system API.

Parameters

NameTypeMandatoryDescription
versionnumberYesVersion of the user authentication widget.

Return value

TypeDescription
UserAuthWidgetMgrUserAuthWidgetMgr instance obtained.

Error codes

For details about the error codes, see User Authentication Error Codes.

IDError Message
201Permission verification failed.
202The caller is not a system application.
401Incorrect parameters.
12500002General operation error.

Example

import userAuth from '@ohos.userIAM.userAuth';

let userAuthWidgetMgrVersion = 1;
try {
  let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion);
  console.log('get userAuthWidgetMgr instance success');
} catch (error) {
  console.log('userAuth widgetMgr catch error: ' + JSON.stringify(error));
}

IAuthWidgetCallback10+

Provides the callback for returning the commands sent from the user authentication framework to the user authentication widget.

sendCommand10+

sendCommand(cmdData: string): void

Called to return the command sent from the user authentication framework to the user authentication widget.

System capability: SystemCapability.UserIAM.UserAuth.Core

System API: This is a system API.

Parameters

NameTypeMandatoryDescription
cmdDatastringYesCommand sent from the user identity authentication framework to the user authentication widget.

Example

import userAuth from '@ohos.userIAM.userAuth';

const userAuthWidgetMgrVersion = 1;
try {
  let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion);
  console.log('get userAuthWidgetMgr instance success');
  userAuthWidgetMgr.on('command', {
    sendCommand(cmdData) {
      console.log('The cmdData is ' + cmdData);
    }
  })
  console.log('subscribe authentication event success');
} catch (error) {
  console.log('userAuth widgetMgr catch error: ' + JSON.stringify(error));
}

AuthResultInfo9+

Defines the authentication result.

System capability: SystemCapability.UserIAM.UserAuth.Core

NameTypeMandatoryDescription
resultnumberYesAuthentication result.
tokenUint8ArrayNoToken that has passed the user identity authentication.
remainAttemptsnumberNoNumber of remaining authentication attempts.
lockoutDurationnumberNoLock duration of the authentication operation, in milliseconds.

TipInfo9+

Defines the authentication tip information.

System capability: SystemCapability.UserIAM.UserAuth.Core

NameTypeMandatoryDescription
modulenumberYesID of the module that sends the tip information.
tipnumberYesTip to be given during the authentication process.

EventInfo9+

Enumerates the authentication event information types.

System capability: SystemCapability.UserIAM.UserAuth.Core

ValueDescription
AuthResultInfoAuthentication result.
TipInfoAuthentication tip information.

AuthEventKey9+

Defines the keyword of the authentication event type. It is used as a parameter of on.

System capability: SystemCapability.UserIAM.UserAuth.Core

ValueDescription
"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.

AuthEvent9+

Provides an asynchronous callback to return the authentication event information.

callback9+

callback(result : EventInfo) : void

Called to return the authentication result or authentication tip information.

System capability: SystemCapability.UserIAM.UserAuth.Core

Parameters

NameTypeMandatoryDescription
resultEventInfoYesAuthentication result or tip information.

Example

import userIAM_userAuth from '@ohos.userIAM.userAuth';

let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
let authType = userIAM_userAuth.UserAuthType.FACE;
let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
// Obtain the authentication result through a callback.
try {
  let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
  auth.on('result', {
    callback: (result: userIAM_userAuth.AuthResultInfo) => {
      console.log('authV9 result ' + result.result);
      console.log('authV9 token ' + result.token);
      console.log('authV9 remainAttempts ' + result.remainAttempts);
      console.log('authV9 lockoutDuration ' + result.lockoutDuration);
    }
  } as userIAM_userAuth.AuthEvent);
  auth.start();
  console.log('authV9 start success');
} catch (error) {
  console.log('authV9 error = ' + error);
  // do error
}
// Obtain the authentication tip information through a callback.
try {
  let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
  auth.on('tip', {
    callback : (result : userIAM_userAuth.TipInfo) => {
      switch (result.tip) {
        case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT:
          // Do something;
        case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK:
          // Do something.
        default:
          // Do others.
      }
    }
  } as userIAM_userAuth.AuthEvent);
  auth.start();
  console.log('authV9 start success');
} catch (error) {
  console.log('authV9 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.

NOTE
Use the AuthInstance instance obtained to invoke this API to subscribe to events.

System capability: SystemCapability.UserIAM.UserAuth.Core

Parameters

NameTypeMandatoryDescription
nameAuthEventKeyYesAuthentication 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.
callbackAuthEventYesCallback invoked to return the authentication result or tip information.

Error codes

For details about the error codes, see User Authentication Error Codes.

IDError Message
401Incorrect parameters.
12500002General operation error.

Example

import userIAM_userAuth from '@ohos.userIAM.userAuth';

let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
let authType = userIAM_userAuth.UserAuthType.FACE;
let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
try {
  let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
  // Subscribe to the authentication result.
  auth.on('result', {
    callback: (result: userIAM_userAuth.AuthResultInfo) => {
      console.log('authV9 result ' + result.result);
      console.log('authV9 token ' + result.token);
      console.log('authV9 remainAttempts ' + result.remainAttempts);
      console.log('authV9 lockoutDuration ' + result.lockoutDuration);
    }
  });
  // Subscribe to authentication tip information.
  auth.on('tip', {
    callback : (result : userIAM_userAuth.TipInfo) => {
      switch (result.tip) {
        case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT:
          // Do something.
        case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK:
          // Do something.
        default:
          // Do others.
      }
    }
  } as userIAM_userAuth.AuthEvent);
  auth.start();
  console.log('authV9 start success');
} catch (error) {
  console.log('authV9 error = ' + error);
  // do error
}

off(deprecated)

off : (name : AuthEventKey) => void

Unsubscribes from the user authentication events of the specific type.

NOTE
This API is supported since API version 9 and deprecated since API version 10.

Use the AuthInstance instance obtained to invoke this API to unsubscribe from events.

System capability: SystemCapability.UserIAM.UserAuth.Core

NameTypeMandatoryDescription
nameAuthEventKeyYesType of the authentication event to unsubscribe from. 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 User Authentication Error Codes.

IDError Message
401Incorrect parameters.
12500002General operation error.

Example

import userIAM_userAuth from '@ohos.userIAM.userAuth';

let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
let authType = userIAM_userAuth.UserAuthType.FACE;
let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
try {
  let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
  // Subscribe to the authentication result.
  auth.on('result', {
    callback: (result: userIAM_userAuth.AuthResultInfo) => {
      console.log('authV9 result ' + result.result);
      console.log('authV9 token ' + result.token);
      console.log('authV9 remainAttempts ' + result.remainAttempts);
      console.log('authV9 lockoutDuration ' + result.lockoutDuration);
    }
  });
  // Unsubscription result.
  auth.off('result');
  console.info('cancel subscribe authentication event success');
} catch (error) {
  console.info('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 the AuthInstance instance obtained to invoke this API.

Required permissions: ohos.permission.ACCESS_BIOMETRIC

System capability: SystemCapability.UserIAM.UserAuth.Core

Error codes

For details about the error codes, see User Authentication Error Codes.

IDError Message
201Permission verification failed.
401Incorrect parameters.
12500001Authentication failed.
12500002General operation error.
12500003The operation is canceled.
12500004The operation is time-out.
12500005The authentication type is not supported.
12500006The authentication trust level is not supported.
12500007The authentication task is busy.
12500009The authenticator is locked.
12500010The type of credential has not been enrolled.

Example

import userIAM_userAuth from '@ohos.userIAM.userAuth';

let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
let authType = userIAM_userAuth.UserAuthType.FACE;
let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;

try {
  let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
  auth.start();
  console.info('authV9 start auth success');
} catch (error) {
  console.info('authV9 start 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 the AuthInstance instance obtained to invoke 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 User Authentication Error Codes.

IDError Message
201Permission verification failed.
401Incorrect parameters.
12500002General operation error.

Example

import userIAM_userAuth from '@ohos.userIAM.userAuth';

let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
let authType = userIAM_userAuth.UserAuthType.FACE;
let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;

try {
  let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
  auth.cancel();
  console.info('cancel auth success');
} catch (error) {
  console.info('cancel auth failed, error = ' + error);
}

userIAM_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 an authentication only once.

System capability: SystemCapability.UserIAM.UserAuth.Core

Parameters

NameTypeMandatoryDescription
challengeUint8ArrayYesChallenge value. It cannot exceed 32 bytes and can be passed in Uint8Array([]) format.
authTypeUserAuthTypeYesAuthentication type. Only FACE is supported.
authTrustLevelAuthTrustLevelYesAuthentication trust level.

Return value

TypeDescription
AuthInstanceAuthInstance instance obtained.

Error codes

For details about the error codes, see User Authentication Error Codes.

IDError Message
401Incorrect parameters.
12500002General operation error.
12500005The authentication type is not supported.
12500006The authentication trust level is not supported.

Example

import userIAM_userAuth from '@ohos.userIAM.userAuth';

let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
let authType = userIAM_userAuth.UserAuthType.FACE;
let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;

try {
  let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
  console.info('let auth instance success');
} catch (error) {
  console.info('get auth instance success failed, error = ' + error);
}

userIAM_userAuth.getAvailableStatus9+

getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel): void

Checks whether the specified authentication capability is supported.

Required permissions: ohos.permission.ACCESS_BIOMETRIC

System capability: SystemCapability.UserIAM.UserAuth.Core

Parameters

NameTypeMandatoryDescription
authTypeUserAuthTypeYesAuthentication type.
authTrustLevelAuthTrustLevelYesAuthentication trust level.

Error codes

For details about the error codes, see User Authentication Error Codes.

IDError Message
201Permission verification failed.
401Incorrect parameters.
12500002General operation error.
12500005The authentication type is not supported.
12500006The authentication trust level is not supported.
12500010The type of credential has not been enrolled.

Example

import userIAM_userAuth from '@ohos.userIAM.userAuth';

try {
  userIAM_userAuth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1);
  console.info('current auth trust level is supported');
} catch (error) {
  console.info('current auth trust level is not supported, error = ' + error);
}

UserAuthResultCode9+

Enumerates the authentication result codes.

System capability: SystemCapability.UserIAM.UserAuth.Core

NameValueDescription
SUCCESS12500000The authentication is successful.
FAIL12500001The authentication failed.
GENERAL_ERROR12500002A general operation error occurred.
CANCELED12500003The authentication is canceled.
TIMEOUT12500004The authentication timed out.
TYPE_NOT_SUPPORT12500005The authentication type is not supported.
TRUST_LEVEL_NOT_SUPPORT12500006The authentication trust level is not supported.
BUSY12500007Indicates the busy state.
LOCKED12500009The authentication executor is locked.
NOT_ENROLLED12500010The user has not entered the authentication information.
CANCELED_FROM_WIDGET10+12500011The authentication is canceled by the user from the user authentication widget. If this error code is returned, the authentication is customized by the application.

UserAuth(deprecated)

Provides APIs for user authentication.

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

Return value

TypeDescription
UserAuthUserAuth instance created.

Example

import userIAM_userAuth from '@ohos.userIAM.userAuth';

let auth = new userIAM_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

TypeDescription
numberAuthenticator version obtained.

Example

import userIAM_userAuth from '@ohos.userIAM.userAuth';

let auth = new userIAM_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. You are advised to use getAvailableStatus.

Required permissions: ohos.permission.ACCESS_BIOMETRIC

System capability: SystemCapability.UserIAM.UserAuth.Core

Parameters

NameTypeMandatoryDescription
authTypeUserAuthTypeYesAuthentication type. Only FACE is supported.
authTrustLevelAuthTrustLevelYesAuthentication trust level.

Return value

TypeDescription
numberQuery result. If the authentication capability is supported, SUCCESS is returned. Otherwise, a ResultCode is returned.

Example

import userIAM_userAuth from '@ohos.userIAM.userAuth';

let auth = new userIAM_userAuth.UserAuth();
let checkCode = auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1);
if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) {
  console.info('check auth support success');
} else {
  console.error('check auth support fail, code = ' + checkCode);
}

auth(deprecated)

auth(challenge: Uint8Array, authType: UserAuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array

Performs 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

NameTypeMandatoryDescription
challengeUint8ArrayYesChallenge value, which can be passed in Uint8Array([]) format.
authTypeUserAuthTypeYesAuthentication type. Only FACE is supported.
authTrustLevelAuthTrustLevelYesAuthentication trust level.
callbackIUserAuthCallbackYesCallback used to return the result.

Return value

TypeDescription
Uint8ArrayContext ID, which is used as the input parameter of cancelAuth.

Example

import userIAM_userAuth from '@ohos.userIAM.userAuth';

let auth = new userIAM_userAuth.UserAuth();
let challenge = new Uint8Array([]);
auth.auth(challenge, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, {
  onResult: (result, extraInfo) => {
    try {
      console.info('auth onResult result = ' + result);
      console.info('auth onResult extraInfo = ' + JSON.stringify(extraInfo));
      if (result == userIAM_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 (e) {
      console.info('auth onResult error = ' + e);
    }
  }
});

cancelAuth(deprecated)

cancelAuth(contextID : Uint8Array) : number

Cancels an 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

NameTypeMandatoryDescription
contextIDUint8ArrayYesContext ID, which is obtained by auth.

Return value

TypeDescription
numberReturns SUCCESS if the cancellation is successful. Returns a ResultCode otherwise.

Example

import userIAM_userAuth from '@ohos.userIAM.userAuth';

// contextId can be obtained by auth(). In this example, it is defined here.
let contextId = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]);
let auth = new userIAM_userAuth.UserAuth();
let cancelCode = auth.cancelAuth(contextId);
if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) {
  console.info('cancel auth success');
} else {
  console.error('cancel auth fail');
}

IUserAuthCallback(deprecated)

Provides callbacks to return the authentication result.

NOTE
This object is supported since API version 8 and deprecated since API version 9. You are advised to use AuthEvent.

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. You are advised to use callback.

System capability: SystemCapability.UserIAM.UserAuth.Core

Parameters

NameTypeMandatoryDescription
resultnumberYesAuthentication result. For details, see ResultCode.
extraInfoAuthResultYesExtended 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 userIAM_userAuth from '@ohos.userIAM.userAuth';

let auth = new userIAM_userAuth.UserAuth();
let challenge = new Uint8Array([]);
auth.auth(challenge, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, {
  onResult: (result, extraInfo) => {
    try {
      console.info('auth onResult result = ' + result);
      console.info('auth onResult extraInfo = ' + JSON.stringify(extraInfo));
      if (result == userIAM_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 (e) {
      console.info('auth onResult error = ' + e);
    }
  }
});

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. You are advised to use callback.

System capability: SystemCapability.UserIAM.UserAuth.Core

Parameters

NameTypeMandatoryDescription
modulenumberYesID of the module that sends the tip information.
acquirenumberYesAuthentication tip information.
extraInfoanyYesReserved field.

Example

import userIAM_userAuth from '@ohos.userIAM.userAuth';

let auth = new userIAM_userAuth.UserAuth();
let challenge = new Uint8Array([]);
auth.auth(challenge, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, {
  onResult: (result, extraInfo) => {
    try {
      console.info('auth onResult result = ' + result);
      console.info('auth onResult extraInfo = ' + JSON.stringify(extraInfo));
      if (result == userIAM_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 (e) {
      console.info('auth onResult error = ' + e);
    }
  },
  onAcquireInfo: (module, acquire, extraInfo : userIAM_userAuth.AuthResult) => {
    try {
      console.info('auth onAcquireInfo module = ' + module);
      console.info('auth onAcquireInfo acquire = ' + acquire);
      console.info('auth onAcquireInfo extraInfo = ' + JSON.stringify(extraInfo));
    } catch (e) {
      console.info('auth onAcquireInfo error = ' + e);
    }
  }
});

AuthResult(deprecated)

Represents the authentication result object.

NOTE
This object is supported since API version 8 and deprecated since API version 9. You are advised to use AuthResultInfo.

System capability: SystemCapability.UserIAM.UserAuth.Core

NameTypeMandatoryDescription
tokenUint8ArrayNoAuthentication token information.
remainTimesnumberNoNumber of remaining authentication operations.
freezingTimenumberNoTime for which the authentication operation is frozen.

ResultCode(deprecated)

Enumerates the authentication result codes.

NOTE
This object is deprecated since API version 9. You are advised to use UserAuthResultCode.

System capability: SystemCapability.UserIAM.UserAuth.Core

NameValueDescription
SUCCESS0The operation is successful.
FAIL1The authentication failed.
GENERAL_ERROR2A general operation error occurred.
CANCELED3The authentication is canceled.
TIMEOUT4The authentication timed out.
TYPE_NOT_SUPPORT5The authentication type is not supported.
TRUST_LEVEL_NOT_SUPPORT6The authentication trust level is not supported.
BUSY7Indicates the busy state.
INVALID_PARAMETERS8Invalid parameters are detected.
LOCKED9The authentication executor is locked.
NOT_ENROLLED10The user has not entered the authentication information.

FaceTips8+

Enumerates the tip codes used during the facial authentication process.

System capability: SystemCapability.UserIAM.UserAuth.Core

NameValueDescription
FACE_AUTH_TIP_TOO_BRIGHT1The obtained facial image is too bright due to high illumination.
FACE_AUTH_TIP_TOO_DARK2The obtained facial image is too dark due to low illumination.
FACE_AUTH_TIP_TOO_CLOSE3The face is too close to the device.
FACE_AUTH_TIP_TOO_FAR4The face is too far away from the device.
FACE_AUTH_TIP_TOO_HIGH5Only the upper part of the face is captured because the device is angled too high.
FACE_AUTH_TIP_TOO_LOW6Only the lower part of the face is captured because the device is angled too low.
FACE_AUTH_TIP_TOO_RIGHT7Only the right part of the face is captured because the device is deviated to the right.
FACE_AUTH_TIP_TOO_LEFT8Only the left part of the face is captured because the device is deviated to the left.
FACE_AUTH_TIP_TOO_MUCH_MOTION9The face moves too fast during facial information collection.
FACE_AUTH_TIP_POOR_GAZE10The face is not facing the camera.
FACE_AUTH_TIP_NOT_DETECTED11No face is detected.

FingerprintTips8+

Enumerates the tip codes used during the fingerprint authentication process.

System capability: SystemCapability.UserIAM.UserAuth.Core

NameValueDescription
FINGERPRINT_AUTH_TIP_GOOD0The obtained fingerprint image is in good condition.
FINGERPRINT_AUTH_TIP_DIRTY1Large fingerprint image noise is detected due to suspicious or detected dirt on the sensor.
FINGERPRINT_AUTH_TIP_INSUFFICIENT2The noise of the fingerprint image is too large to be processed.
FINGERPRINT_AUTH_TIP_PARTIAL3Incomplete fingerprint image is detected.
FINGERPRINT_AUTH_TIP_TOO_FAST4The fingerprint image is incomplete due to fast movement.
FINGERPRINT_AUTH_TIP_TOO_SLOW5Failed to obtain the fingerprint image because the finger seldom moves.

UserAuthType8+

Enumerates the identity authentication types.

System capability: SystemCapability.UserIAM.UserAuth.Core

NameValueDescription
PIN10+1PIN authentication.
FACE2Facial authentication.
FINGERPRINT4Fingerprint authentication.

AuthTrustLevel8+

Enumerates the trust levels of the authentication result.

System capability: SystemCapability.UserIAM.UserAuth.Core

NameValueDescription
ATL110000Authentication 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.
ATL220000Authentication 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 logins to apps and keeping a device in unlocked state.
ATL330000Authentication 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.
ATL440000Authentication 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.

userIAM_userAuth.getAuthenticator(deprecated)

getAuthenticator(): Authenticator

Obtains an Authenticator instance for user authentication.

NOTE
This API is deprecated since API version 8. You are advised to use constructor.

System capability: SystemCapability.UserIAM.UserAuth.Core

Return value

TypeDescription
AuthenticatorAuthenticator instance obtained.

Example

import userIAM_userAuth from '@ohos.userIAM.userAuth';

let authenticator = userIAM_userAuth.getAuthenticator();

Authenticator(deprecated)

Defines the Authenticator object.

NOTE
This API is deprecated since API version 8. Use UserAuth instead.

execute(deprecated)

execute(type: AuthType, level: SecureLevel, callback: AsyncCallback<number>): void

Performs user authentication. This API uses asynchronous callback to return the result.

NOTE
This API is deprecated since API version 8. You are advised to use auth.

Required permissions: ohos.permission.ACCESS_BIOMETRIC

System capability: SystemCapability.UserIAM.UserAuth.Core

Parameters

NameTypeMandatoryDescription
typeAuthTypeYesAuthentication type. Only FACE_ONLY is supported.
ALL is reserved and not supported by the current version.
levelSecureLevelYesSecurity 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.
callbackAsyncCallback<number>YesCallback used to return the result.

Parameters returned in callback

TypeDescription
numberAuthentication result. For details, see AuthenticationResult.

Example

import userIAM_userAuth from '@ohos.userIAM.userAuth';

let authenticator = userIAM_userAuth.getAuthenticator();
authenticator.execute('FACE_ONLY', 'S2', (error, code)=>{
  if (code === userIAM_userAuth.ResultCode.SUCCESS) {
    console.info('auth success');
    return;
  }
  console.error('auth fail, code = ' + code);
});

execute(deprecated)

execute(type : AuthType, level : SecureLevel): Promise<number>

Performs user authentication. This API uses a promise to return the result.

NOTE
This API is deprecated since API version 8. You are advised to use auth.

Required permissions: ohos.permission.ACCESS_BIOMETRIC

System capability: SystemCapability.UserIAM.UserAuth.Core

Parameters

NameTypeMandatoryDescription
typeAuthTypeYesAuthentication type. Only FACE_ONLY is supported.
ALL is reserved and not supported by the current version.
levelSecureLevelYesSecurity 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

TypeDescription
Promise<number>Promise used to return the authentication result, which is a number. For details, see AuthenticationResult.

Example

import userIAM_userAuth from '@ohos.userIAM.userAuth';

try {
  let authenticator = userIAM_userAuth.getAuthenticator();
  authenticator.execute('FACE_ONLY', 'S2').then((code)=>{
    console.info('auth success');
  })
} catch (error) {
  console.error('auth fail, code = ' + error);
}

AuthenticationResult(deprecated)

Enumerates the authentication results.

NOTE
This object is discarded since API version 8. You are advised to use ResultCode.

System capability: SystemCapability.UserIAM.UserAuth.Core

NameValueDescription
NO_SUPPORT-1The device does not support the current authentication mode.
SUCCESS0The authentication is successful.
COMPARE_FAILURE1The feature comparison failed.
CANCELED2The authentication was canceled by the user.
TIMEOUT3The authentication has timed out.
CAMERA_FAIL4The camera failed to start.
BUSY5The authentication service is not available. Try again later.
INVALID_PARAMETERS6The authentication parameters are invalid.
LOCKED7The user account is locked because the number of authentication failures has reached the threshold.
NOT_ENROLLED8No authentication credential is registered.
GENERAL_ERROR100Other errors.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙APIs

harmony 鸿蒙System Common Events (To Be Deprecated Soon)

harmony 鸿蒙System Common Events

harmony 鸿蒙API Reference Document Description

harmony 鸿蒙Enterprise Device Management Overview (for System Applications Only)

harmony 鸿蒙BundleStatusCallback

harmony 鸿蒙@ohos.bundle.innerBundleManager (innerBundleManager)

harmony 鸿蒙@ohos.distributedBundle (Distributed Bundle Management)

harmony 鸿蒙@ohos.bundle (Bundle)

harmony 鸿蒙@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/1ac300f5cc3643debbe0803e082620a0