• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.userIAM.userAuth (User Authentication)
2
3The **userIAM.userAuth** module provides user authentication capabilities in identity authentication scenarios, such as device unlocking, payment, and app login.
4
5> **NOTE**<br>
6> 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.
7
8
9## Modules to Import
10
11```ts
12import { userAuth } from '@kit.UserAuthenticationKit';
13```
14
15## Constant
16
17Represents the maximum period for which the device unlocking result can be reused.
18
19**Atomic service API**: This API can be used in atomic services since API version 12.
20
21**System capability**: SystemCapability.UserIAM.UserAuth.Core
22
23| Name       | Value  | Description      |
24| ----------- | ---- | ---------- |
25| MAX_ALLOWABLE_REUSE_DURATION<sup>12+</sup>    | 300000   | Maximum period for which the device unlocking result can be reused. The value is **300,000** ms.|
26
27## EnrolledState<sup>12+</sup>
28
29Represents information about the enrolled credentials.
30
31**Atomic service API**: This API can be used in atomic services since API version 12.
32
33**System capability**: SystemCapability.UserIAM.UserAuth.Core
34
35| Name        | Type   | Readable| Writable| Description                |
36| ------------ | ---------- | ---- | ---- | -------------------- |
37| credentialDigest       | number | Yes  |  No| Credential digest, which is randomly generated when a credential is added.|
38| credentialCount        | number | Yes  |  No| Number of enrolled credentials.      |
39
40## ReuseMode<sup>12+</sup>
41
42Represents the mode for reusing the device unlocking result.
43
44**System capability**: SystemCapability.UserIAM.UserAuth.Core
45
46| Name       | Value  | Description      |
47| ----------- | ---- | ---------- |
48| AUTH_TYPE_RELEVANT    | 1   | The device unlocking result can be reused within the validity period if the authentication type matches any of the authentication types specified for this authentication.<br> **Atomic service API**: This API can be used in atomic services since API version 12.|
49| AUTH_TYPE_IRRELEVANT  | 2   | The device unlocking result can be reused within the validity period regardless of the authentication type.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
50| CALLER_IRRELEVANT_AUTH_TYPE_RELEVANT<sup>14+</sup>    | 3   | Any identity authentication (including device unlocking) result can be reused within the validity period if the authentication type matches any of the authentication types specified for this authentication.<br>**Atomic service API**: This API can be used in atomic services since API version 14.|
51| CALLER_IRRELEVANT_AUTH_TYPE_IRRELEVANT<sup>14+</sup>  | 4   | Any identity authentication (including device unlocking) result can be reused within the validity period regardless of the authentication type.<br>**Atomic service API**: This API can be used in atomic services since API version 14.|
52
53## ReuseUnlockResult<sup>12+</sup>
54
55Represents the device unlocking result.
56> **NOTE**
57>
58> If the credential changes within the validity period after the screen is unlocked, the screen lock authentication result can still be reused, and the actual **EnrolledState** is returned in the authentication result. If the credential is completely deleted when the lock screen authentication result is reused,
59> both **credentialCount** and **credentialDigest** in **EnrolledState** are **0**.
60
61**Atomic service API**: This API can be used in atomic services since API version 12.
62
63**System capability**: SystemCapability.UserIAM.UserAuth.Core
64
65| Name        | Type  | Mandatory| Description                |
66| ------------ | ---------- | ---- | -------------------- |
67| reuseMode        | [ReuseMode](#reusemode12) | Yes  | Mode for reusing the device unlocking result.      |
68| reuseDuration    | number | Yes  | Period for which the device unlocking result can be reused. <br>Value range: 0 to [MAX_ALLOWABLE_REUSE_DURATION](#constant)|
69
70## userAuth.getEnrolledState<sup>12+</sup>
71
72getEnrolledState(authType : UserAuthType): EnrolledState
73
74Obtains information about the credentials enrolled. With this API, you can obtain the change of the credentials.
75
76**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
77
78**Atomic service API**: This API can be used in atomic services since API version 12.
79
80**System capability**: SystemCapability.UserIAM.UserAuth.Core
81
82**Parameters**
83
84| Name        | Type                              | Mandatory| Description                      |
85| -------------- | ---------------------------------- | ---- | -------------------------- |
86| authType       | [UserAuthType](#userauthtype8)     | Yes  | Authentication type.|
87
88**Return value**
89
90| Type                 | Description                                                        |
91| --------------------- | ------------------------------------------------------------ |
92| [EnrolledState](#enrolledstate12) | Information about the enrolled credentials.|
93
94**Error codes**
95
96For details about the error codes, see [User Authentication Error Codes](errorcode-useriam.md).
97
98| ID| Error Message|
99| -------- | ------- |
100| 201 | Permission verification failed. |
101| 401 | Incorrect parameters. Possible causes: 1.Mandatory parameters are left unspecified. |
102| 12500002 | General operation error. |
103| 12500005 | The authentication type is not supported. |
104| 12500010 | The type of credential has not been enrolled. |
105
106**Example**
107
108```ts
109import { userAuth } from '@kit.UserAuthenticationKit';
110
111try {
112  let enrolledState = userAuth.getEnrolledState(userAuth.UserAuthType.FACE);
113  console.info(`get current enrolled state success, enrolledState = ${JSON.stringify(enrolledState)}`);
114} catch (error) {
115  console.error(`get current enrolled state failed, error = ${JSON.stringify(error)}`);
116}
117```
118
119## AuthParam<sup>10+</sup>
120
121Defines the user authentication parameters.
122
123**Atomic service API**: This API can be used in atomic services since API version 12.
124
125**System capability**: SystemCapability.UserIAM.UserAuth.Core
126
127| Name          | Type                              | Mandatory| Description                                                        |
128| -------------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
129| challenge      | Uint8Array                         | Yes  | Random challenge value, which is used to prevent replay attacks. It cannot exceed 32 bytes and can be passed in **Uint8Array([])** format.|
130| authType       | [UserAuthType](#userauthtype8)[]   | Yes  | Authentication type list, which specifies the types of authentication provided on the user authentication page.          |
131| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes  | Authentication trust level.                                              |
132| reuseUnlockResult<sup>12+</sup> | [ReuseUnlockResult](#reuseunlockresult12) | No  |Device unlocking result that can be reused.|
133
134## WidgetParam<sup>10+</sup>
135
136Represents the information presented on the user authentication page.
137
138**System capability**: SystemCapability.UserIAM.UserAuth.Core
139
140| Name                | Type                               | Mandatory| Description                                                        |
141| -------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ |
142| title                | string                              | Yes  | Title of the user authentication page. It cannot exceed 500 characters.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
143| navigationButtonText | string                              | No  | Text on the navigation button. It cannot exceed 60 characters. This parameter is valid only in fingerprint or facial authentication only.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
144| uiContext<sup>16+</sup>            | Context               | No  | Whether to display the authentication dialog box in modal application mode. 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 in modal system mode.<br>**Atomic service API**: This API can be used in atomic services since API version 16.|
145
146## UserAuthResult<sup>10+</sup>
147
148Represents the user authentication result. If the authentication is successful, the authentication type and token information are returned.
149
150**Atomic service API**: This API can be used in atomic services since API version 12.
151
152**System capability**: SystemCapability.UserIAM.UserAuth.Core
153
154| Name    | Type                          | Mandatory| Description                                                        |
155| -------- | ------------------------------ | ---- | ------------------------------------------------------------ |
156| result   | number                         | Yes  | User authentication result. If the operation is successful, **SUCCESS** is returned. If the operation fails, an error code is returned. For details, see [UserAuthResultCode](#userauthresultcode9).|
157| token    | Uint8Array                     | No  | Token that has passed the authentication.                |
158| authType | [UserAuthType](#userauthtype8) | No  | Type of the authentication.                          |
159| enrolledState<sup>12+</sup> | [EnrolledState](#enrolledstate12) | No  |  Enrolled credential information.        |
160
161## IAuthCallback<sup>10+</sup>
162
163Provides callbacks to return the authentication result.
164
165### onResult<sup>10+</sup>
166
167onResult(result: UserAuthResult): void
168
169Called to return the authentication result. If the authentication is successful, the token information can be obtained from **UserAuthResult**.
170
171**Atomic service API**: This API can be used in atomic services since API version 12.
172
173**System capability**: SystemCapability.UserIAM.UserAuth.Core
174
175**Parameters**
176
177| Name| Type                               | Mandatory| Description      |
178| ------ | ----------------------------------- | ---- | ---------- |
179| result | [UserAuthResult](#userauthresult10) | Yes  | Authentication result.|
180
181**Example 1**
182
183Initiate facial authentication and lock screen password authentication with the authentication trust level greater than or equal to ATL3.
184
185```ts
186import { BusinessError } from '@kit.BasicServicesKit';
187import { cryptoFramework } from '@kit.CryptoArchitectureKit';
188import { userAuth } from '@kit.UserAuthenticationKit';
189
190try {
191  const rand = cryptoFramework.createRandom();
192  const len: number = 16;
193  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
194  const authParam: userAuth.AuthParam = {
195    challenge: randData,
196    authType: [userAuth.UserAuthType.PIN],
197    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
198  };
199  const widgetParam: userAuth.WidgetParam = {
200    title:'Enter password',
201  };
202
203  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
204  console.info('get userAuth instance success');
205  // The authentication result is returned by onResult only after the authentication is started by start() of UserAuthInstance.
206  userAuthInstance.on('result', {
207    onResult (result) {
208      console.info(`userAuthInstance callback result = ${JSON.stringify(result)}`);
209    }
210  });
211  console.info('auth on success');
212} catch (error) {
213  const err: BusinessError = error as BusinessError;
214  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
215}
216```
217
218**Example 2**
219
220Initiate facial authentication with the authentication trust level greater than or equal to ATL3, and enable the device unlock result to be reused for the same type of authentication within the specified time.
221
222```ts
223import { BusinessError } from '@kit.BasicServicesKit';
224import { cryptoFramework } from '@kit.CryptoArchitectureKit';
225import { userAuth } from '@kit.UserAuthenticationKit';
226
227let reuseUnlockResult: userAuth.ReuseUnlockResult = {
228  reuseMode: userAuth.ReuseMode.AUTH_TYPE_RELEVANT,
229  reuseDuration: userAuth.MAX_ALLOWABLE_REUSE_DURATION,
230}
231try {
232  const rand = cryptoFramework.createRandom();
233  const len: number = 16;
234  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
235  const authParam: userAuth.AuthParam = {
236    challenge: randData,
237    authType: [userAuth.UserAuthType.PIN],
238    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
239    reuseUnlockResult: reuseUnlockResult,
240  };
241  const widgetParam: userAuth.WidgetParam = {
242    title:'Enter password',
243  };
244  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
245  console.info('get userAuth instance success');
246  // The authentication result is returned by onResult only after the authentication is started by start() of UserAuthInstance.
247  userAuthInstance.on('result', {
248    onResult (result) {
249      console.info(`userAuthInstance callback result = ${JSON.stringify(result)}`);
250    }
251  });
252  console.info('auth on success');
253} catch (error) {
254  const err: BusinessError = error as BusinessError;
255  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
256}
257```
258
259**Example 3**
260
261Initiate facial authentication with the authentication trust level greater than or equal to ATL3, and enable the device unlock result to be reused for any type of authentication within the maximum authentication validity of any application.
262
263```ts
264import { BusinessError } from '@kit.BasicServicesKit';
265import { cryptoFramework } from '@kit.CryptoArchitectureKit';
266import { userAuth } from '@kit.UserAuthenticationKit';
267
268let reuseUnlockResult: userAuth.ReuseUnlockResult = {
269  reuseMode: userAuth.ReuseMode.CALLER_IRRELEVANT_AUTH_TYPE_RELEVANT,
270  reuseDuration: userAuth.MAX_ALLOWABLE_REUSE_DURATION,
271}
272try {
273  const rand = cryptoFramework.createRandom();
274  const len: number = 16;
275  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
276  const authParam: userAuth.AuthParam = {
277    challenge: randData,
278    authType: [userAuth.UserAuthType.PIN],
279    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
280    reuseUnlockResult: reuseUnlockResult,
281  };
282  const widgetParam: userAuth.WidgetParam = {
283    title:'Enter password',
284  };
285  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
286  console.info('get userAuth instance success');
287  // The authentication result is returned by onResult only after the authentication is started by start() of UserAuthInstance.
288  userAuthInstance.on('result', {
289    onResult (result) {
290      console.info(`userAuthInstance callback result = ${JSON.stringify(result)}`);
291    }
292  });
293  console.info('auth on success');
294} catch (error) {
295  const err: BusinessError = error as BusinessError;
296  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
297}
298```
299
300## UserAuthInstance<sup>10+</sup>
301
302Provides APIs for user authentication. The user authentication widget is supported.
303Before using the APIs, you need to obtain a **UserAuthInstance** instance by using [getUserAuthInstance](#userauthgetuserauthinstance10).
304
305### on<sup>10+</sup>
306
307on(type: 'result', callback: IAuthCallback): void
308
309Subscribes to the user authentication result.
310
311**Atomic service API**: This API can be used in atomic services since API version 12.
312
313**System capability**: SystemCapability.UserIAM.UserAuth.Core
314
315**Parameters**
316
317| Name  | Type                             | Mandatory| Description                                      |
318| -------- | --------------------------------- | ---- | ------------------------------------------ |
319| type     | 'result'                          | Yes  | Event type. The value is **result**, which indicates the authentication result.|
320| callback | [IAuthCallback](#iauthcallback10) | Yes  | Callback used to return the user authentication result.    |
321
322**Error codes**
323
324For details about the error codes, see [User Authentication Error Codes](errorcode-useriam.md).
325
326| ID| Error Message                |
327| -------- | ------------------------ |
328| 401      | Incorrect parameters. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
329| 12500002 | General operation error. |
330
331**Example 1**
332
333Perform user identity authentication in modal system mode.
334
335```ts
336import { BusinessError } from '@kit.BasicServicesKit';
337import { cryptoFramework } from '@kit.CryptoArchitectureKit';
338import { userAuth } from '@kit.UserAuthenticationKit';
339
340try {
341  const rand = cryptoFramework.createRandom();
342  const len: number = 16;
343  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
344  const authParam: userAuth.AuthParam = {
345    challenge: randData,
346    authType: [userAuth.UserAuthType.PIN],
347    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
348  };
349  const widgetParam: userAuth.WidgetParam = {
350    title:'Enter password',
351  };
352  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
353  console.info('get userAuth instance success');
354  // The authentication result is returned by onResult only after the authentication is started by start() of UserAuthInstance.
355  userAuthInstance.on('result', {
356    onResult (result) {
357      console.info(`userAuthInstance callback result = ${JSON.stringify(result)}`);
358    }
359  });
360  console.info('auth on success');
361} catch (error) {
362  const err: BusinessError = error as BusinessError;
363  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
364}
365```
366
367**Example 2**
368
369Perform user identity authentication in modal application mode.
370
371```ts
372import { BusinessError } from '@kit.BasicServicesKit';
373import { cryptoFramework } from '@kit.CryptoArchitectureKit';
374import { userAuth } from '@kit.UserAuthenticationKit';
375
376try {
377  const rand = cryptoFramework.createRandom();
378  const len: number = 16;
379  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
380  const authParam: userAuth.AuthParam = {
381    challenge: randData,
382    authType: [userAuth.UserAuthType.PIN],
383    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
384  };
385  const widgetParam: userAuth.WidgetParam = {
386    title:'Enter password',
387    uiContext: this.getUIContext().getHostContext(),
388  };
389  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
390  console.info('get userAuth instance success');
391  // The authentication result is returned by onResult only after the authentication is started by start() of UserAuthInstance.
392  userAuthInstance.on('result', {
393    onResult (result) {
394      console.info(`userAuthInstance callback result = ${JSON.stringify(result)}`);
395    }
396  });
397  console.info('auth on success');
398} catch (error) {
399  const err: BusinessError = error as BusinessError;
400  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
401}
402```
403
404### off<sup>10+</sup>
405
406off(type: 'result', callback?: IAuthCallback): void
407
408Unsubscribes from the user authentication result.
409
410> **NOTE**
411>
412> The [UserAuthInstance](#userauthinstance10) instance used to invoke this API must be the one used to subscribe to the event.
413
414**Atomic service API**: This API can be used in atomic services since API version 12.
415
416**System capability**: SystemCapability.UserIAM.UserAuth.Core
417
418**Parameters**
419
420| Name  | Type                             | Mandatory| Description                                      |
421| -------- | --------------------------------- | ---- | ------------------------------------------ |
422| type     | 'result'                          | Yes  | Event type. The value is **result**, which indicates the authentication result.|
423| callback | [IAuthCallback](#iauthcallback10) | No  | Callback to unregister.    |
424
425**Error codes**
426
427For details about the error codes, see [User Authentication Error Codes](errorcode-useriam.md).
428
429| ID| Error Message                |
430| -------- | ------------------------ |
431| 401      | Incorrect parameters. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
432| 12500002 | General operation error. |
433
434**Example**
435
436```ts
437import { BusinessError } from '@kit.BasicServicesKit';
438import { cryptoFramework } from '@kit.CryptoArchitectureKit';
439import { userAuth } from '@kit.UserAuthenticationKit';
440
441try {
442  const rand = cryptoFramework.createRandom();
443  const len: number = 16;
444  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
445  const authParam: userAuth.AuthParam = {
446    challenge: randData,
447    authType: [userAuth.UserAuthType.PIN],
448    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
449  };
450  const widgetParam: userAuth.WidgetParam = {
451    title:'Enter password',
452  };
453  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
454  console.info('get userAuth instance success');
455  userAuthInstance.off('result', {
456    onResult (result) {
457      console.info(`auth off result = ${JSON.stringify(result)}`);
458    }
459  });
460  console.info('auth off success');
461} catch (error) {
462  const err: BusinessError = error as BusinessError;
463  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
464}
465```
466
467### start<sup>10+</sup>
468
469start(): void
470
471Starts authentication.
472
473> **NOTE**<br>
474> A **UserAuthInstance** instance can be used for an authentication only once.
475
476**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
477
478**Atomic service API**: This API can be used in atomic services since API version 12.
479
480**System capability**: SystemCapability.UserIAM.UserAuth.Core
481
482**Error codes**
483
484For details about the error codes, see [User Authentication Error Codes](errorcode-useriam.md).
485
486| ID| Error Message                                        |
487| -------- | ------------------------------------------------ |
488| 201      | Permission verification failed.                  |
489| 401      | Incorrect parameters. Possible causes: 1.Incorrect parameter types. |
490| 12500001 | Authentication failed.                           |
491| 12500002 | General operation error.                         |
492| 12500003 | Authentication canceled.                         |
493| 12500004 | Authentication timeout.                          |
494| 12500005 | The authentication type is not supported.        |
495| 12500006 | The authentication trust level is not supported. |
496| 12500007 | Authentication service is busy.                  |
497| 12500009 | Authentication is locked out.                    |
498| 12500010 | The type of credential has not been enrolled.    |
499| 12500011 | Switched to the custom authentication process.   |
500| 12500013 | Operation failed because of PIN expired. |
501
502**Example**
503
504```ts
505import { BusinessError } from '@kit.BasicServicesKit';
506import { cryptoFramework } from '@kit.CryptoArchitectureKit';
507import { userAuth } from '@kit.UserAuthenticationKit';
508
509try {
510  const rand = cryptoFramework.createRandom();
511  const len: number = 16;
512  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
513  const authParam: userAuth.AuthParam = {
514    challenge: randData,
515    authType: [userAuth.UserAuthType.PIN],
516    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
517  };
518  const widgetParam: userAuth.WidgetParam = {
519    title:'Enter password',
520  };
521  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
522  console.info('get userAuth instance success');
523  userAuthInstance.start();
524  console.info('auth start success');
525} catch (error) {
526  const err: BusinessError = error as BusinessError;
527  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
528}
529```
530
531### cancel<sup>10+</sup>
532
533cancel(): void
534
535Cancels this authentication.
536
537> **NOTE**
538>
539> **UserAuthInstance** must be the instance being authenticated.
540
541**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
542
543**Atomic service API**: This API can be used in atomic services since API version 12.
544
545**System capability**: SystemCapability.UserIAM.UserAuth.Core
546
547**Error codes**
548
549| ID| Error Message                       |
550| -------- | ------------------------------- |
551| 201      | Permission verification failed. |
552| 401      | Incorrect parameters. Possible causes: 1.Incorrect parameter types. |
553| 12500002 | General operation error.        |
554
555**Example**
556
557```ts
558import { BusinessError } from '@kit.BasicServicesKit';
559import { cryptoFramework } from '@kit.CryptoArchitectureKit';
560import { userAuth } from '@kit.UserAuthenticationKit';
561
562try {
563  const rand = cryptoFramework.createRandom();
564  const len: number = 16;
565  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
566  const authParam : userAuth.AuthParam = {
567    challenge: randData,
568    authType: [userAuth.UserAuthType.PIN],
569    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
570  };
571  const widgetParam: userAuth.WidgetParam = {
572    title:'Enter password',
573  };
574  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
575  console.info('get userAuth instance success');
576  // The cancel() API can be called only after the authentication is started by start() of UserAuthInstance.
577  userAuthInstance.cancel();
578  console.info('auth cancel success');
579} catch (error) {
580  const err: BusinessError = error as BusinessError;
581  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
582}
583```
584
585## userAuth.getUserAuthInstance<sup>10+</sup>
586
587getUserAuthInstance(authParam: AuthParam, widgetParam: WidgetParam): UserAuthInstance
588
589Obtains a [UserAuthInstance](#userauthinstance10) instance for user authentication. The user authentication widget is also supported.
590
591> **NOTE**<br>
592> A **UserAuthInstance** instance can be used for an authentication only once.
593
594**Atomic service API**: This API can be used in atomic services since API version 12.
595
596**System capability**: SystemCapability.UserIAM.UserAuth.Core
597
598**Parameters**
599
600| Name     | Type                         | Mandatory| Description                      |
601| ----------- | ----------------------------- | ---- | -------------------------- |
602| authParam   | [AuthParam](#authparam10)      | Yes  | User authentication parameters.        |
603| widgetParam | [WidgetParam](#widgetparam10) | Yes  | Parameters on the user authentication page.|
604
605**Return value**
606
607| Type                                   | Description                      |
608| --------------------------------------- | -------------------------- |
609| [UserAuthInstance](#userauthinstance10) | **UserAuthInstance** instance that supports UI.|
610
611**Error codes**
612
613For details about the error codes, see [User Authentication Error Codes](errorcode-useriam.md).
614
615| ID| Error Message                                        |
616| -------- | ------------------------------------------------ |
617| 401      | Incorrect parameters. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.   |
618| 12500002 | General operation error.                         |
619| 12500005 | The authentication type is not supported.        |
620| 12500006 | The authentication trust level is not supported. |
621
622**Example**
623
624```ts
625import { BusinessError } from '@kit.BasicServicesKit';
626import { cryptoFramework } from '@kit.CryptoArchitectureKit';
627import { userAuth } from '@kit.UserAuthenticationKit';
628
629try {
630  const rand = cryptoFramework.createRandom();
631  const len: number = 16;
632  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
633  const authParam: userAuth.AuthParam = {
634    challenge: randData,
635    authType: [userAuth.UserAuthType.PIN],
636    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
637  };
638  const widgetParam: userAuth.WidgetParam = {
639    title:'Enter password',
640  };
641  let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
642  console.info('get userAuth instance success');
643} catch (error) {
644  const err: BusinessError = error as BusinessError;
645  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
646}
647```
648
649## AuthResultInfo<sup>(deprecated)</sup>
650
651Defines the authentication result.
652
653> **NOTE**<br>
654> This API is supported since API version 9 and deprecated since API version 11.
655
656**System capability**: SystemCapability.UserIAM.UserAuth.Core
657
658| Name        | Type  | Mandatory| Description                |
659| ------------ | ---------- | ---- | -------------------- |
660| result        | number | Yes  | Authentication result.      |
661| token        | Uint8Array | No  | Token that has passed the user identity authentication.|
662| remainAttempts  | number     | No  | Number of remaining authentication attempts.|
663| lockoutDuration | number     | No  | Lock duration of the authentication operation, in ms.|
664
665## TipInfo<sup>(deprecated)</sup>
666
667Defines the authentication tip information.
668
669> **NOTE**<br>
670> This API is supported since API version 9 and deprecated since API version 11.
671
672**System capability**: SystemCapability.UserIAM.UserAuth.Core
673
674| Name        | Type  | Mandatory| Description                |
675| ------------ | ---------- | ---- | -------------------- |
676| module        | number | Yes  | ID of the module that sends the tip information.      |
677| tip        | number | Yes  | Tip to be given during the authentication process.      |
678
679## EventInfo<sup>(deprecated)</sup>
680
681type EventInfo = AuthResultInfo | TipInfo
682
683Enumerates the authentication event information types.
684
685The event information type consists of the fields in **Type** in the following table.
686
687> **NOTE**<br>
688> This parameter is supported since API version 9 and deprecated since API version 11. Use [UserAuthResult](#userauthresult10) instead.
689
690**System capability**: SystemCapability.UserIAM.UserAuth.Core
691
692| Type   | Description                      |
693| --------- | ----------------------- |
694| [AuthResultInfo](#authresultinfodeprecated)    | Authentication result. |
695| [TipInfo](#tipinfodeprecated)    | Authentication tip information.     |
696
697## AuthEventKey<sup>(deprecated)</sup>
698
699type AuthEventKey = 'result' | 'tip'
700
701Defines the keyword of the authentication event type. It is used as a parameter of [on](#ondeprecated).
702
703It consists of the fields in **Type** in the following table.
704
705> **NOTE**<br>
706> This API is supported since API version 9 and deprecated since API version 11.
707
708**System capability**: SystemCapability.UserIAM.UserAuth.Core
709
710| Type      | Description                   |
711| ---------- | ----------------------- |
712| 'result' | If the first parameter of [on](#ondeprecated) is **result**, the [callback](#callbackdeprecated) returns the authentication result.|
713| 'tip'    | If the first parameter of [on](#ondeprecated) is **tip**, the [callback](#callbackdeprecated) returns the authentication tip information.|
714
715## AuthEvent<sup>(deprecated)</sup>
716
717Provides an asynchronous callback to return the authentication event information.
718
719> **NOTE**<br>
720> This API is supported since API version 9 and deprecated since API version 11. Use [IAuthCallback](#iauthcallback10) instead.
721
722### callback<sup>(deprecated)</sup>
723
724callback(result : EventInfo) : void
725
726Called to return the authentication result or authentication tip information.
727
728> **NOTE**<br>
729> This API is supported since API version 9 and deprecated since API version 11. Use [onResult](#onresult10) instead.
730
731**System capability**: SystemCapability.UserIAM.UserAuth.Core
732
733**Parameters**
734
735| Name   | Type                      | Mandatory| Description                          |
736| --------- | -------------------------- | ---- | ------------------------------ |
737| result    | [EventInfo](#eventinfodeprecated)     | Yes  | Authentication result or tip information. |
738
739**Example**
740
741```ts
742import { userAuth } from '@kit.UserAuthenticationKit';
743
744let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
745let authType = userAuth.UserAuthType.FACE;
746let authTrustLevel = userAuth.AuthTrustLevel.ATL1;
747// Obtain the authentication result through a callback.
748try {
749  let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
750  auth.on('result', {
751    callback: (result: userAuth.AuthResultInfo) => {
752      console.info(`authV9 result ${result.result}`);
753      console.info(`authV9 token ${result.token}`);
754      console.info(`authV9 remainAttempts ${result.remainAttempts}`);
755      console.info(`authV9 lockoutDuration ${result.lockoutDuration}`);
756    }
757  } as userAuth.AuthEvent);
758  auth.start();
759  console.info('authV9 start success');
760} catch (error) {
761  console.error(`authV9 error = ${error}`);
762  // do error
763}
764// Obtain the authentication tip information through a callback.
765try {
766  let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
767  auth.on('tip', {
768    callback : (result : userAuth.TipInfo) => {
769      switch (result.tip) {
770        case userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT:
771          // Do something.
772        case userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK:
773          // Do something.
774        default:
775          // Do others.
776      }
777    }
778  } as userAuth.AuthEvent);
779  auth.start();
780  console.info('authV9 start success');
781} catch (error) {
782  console.error(`authV9 error = ${error}`);
783  // do error
784}
785```
786
787## AuthInstance<sup>(deprecated)</sup>
788
789Implements user authentication.
790
791> **NOTE**<br>
792> This API is supported since API version 9 and deprecated since API version 10. Use [UserAuthInstance](#userauthinstance10) instead.
793
794### on<sup>(deprecated)</sup>
795
796on : (name : AuthEventKey, callback : AuthEvent) => void
797
798Subscribes to the user authentication events of the specified type.
799
800> **NOTE**<br>
801> - This API is supported since API version 9 and deprecated since API version 10.
802> - Use the [AuthInstance](#authinstancedeprecated) instance obtained to call this API.
803
804**System capability**: SystemCapability.UserIAM.UserAuth.Core
805
806**Parameters**
807
808| Name   | Type                       | Mandatory| Description                      |
809| --------- | -------------------------- | ---- | ------------------------- |
810| name  | [AuthEventKey](#autheventkeydeprecated) | 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.|
811| callback  | [AuthEvent](#autheventdeprecated)   | Yes  | Callback used to return the authentication result or tip information.|
812
813**Error codes**
814
815For details about the error codes, see [User Authentication Error Codes](errorcode-useriam.md).
816
817| ID| Error Message|
818| -------- | ------- |
819| 401 | Incorrect parameters. |
820| 12500002 | General operation error. |
821
822**Example**
823
824```ts
825import { userAuth } from '@kit.UserAuthenticationKit';
826
827let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
828let authType = userAuth.UserAuthType.FACE;
829let authTrustLevel = userAuth.AuthTrustLevel.ATL1;
830try {
831  let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
832  // Subscribe to the authentication result.
833  auth.on('result', {
834    callback: (result: userAuth.AuthResultInfo) => {
835      console.info(`authV9 result ${result.result}`);
836      console.info(`authV9 token ${result.token}`);
837      console.info(`authV9 remainAttempts ${result.remainAttempts}`);
838      console.info(`authV9 lockoutDuration ${result.lockoutDuration}`);
839    }
840  });
841  // Subscribe to authentication tip information.
842  auth.on('tip', {
843    callback : (result : userAuth.TipInfo) => {
844      switch (result.tip) {
845        case userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT:
846          // Do something.
847        case userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK:
848          // Do something.
849        default:
850          // Do others.
851      }
852    }
853  } as userAuth.AuthEvent);
854  auth.start();
855  console.info('authV9 start success');
856} catch (error) {
857  console.error(`authV9 error = ${error}`);
858  // do error
859}
860```
861
862### off<sup>(deprecated)</sup>
863
864off : (name : AuthEventKey) => void
865
866Unsubscribes from the user authentication events of the specific type.
867
868> **NOTE**<br>
869> - This API is supported since API version 9 and deprecated since API version 10.
870> - The [AuthInstance](#authinstancedeprecated) instance used to call this API must be the one used to subscribe to the events.
871
872**System capability**: SystemCapability.UserIAM.UserAuth.Core
873
874| Name   | Type                       | Mandatory| Description                      |
875| --------- | -------------------------- | ---- | ------------------------- |
876| name    | [AuthEventKey](#autheventkeydeprecated)      | 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.|
877
878**Error codes**
879
880For details about the error codes, see [User Authentication Error Codes](errorcode-useriam.md).
881
882| ID| Error Message|
883| -------- | ------- |
884| 401 | Incorrect parameters. |
885| 12500002 | General operation error. |
886
887**Example**
888
889```ts
890import { userAuth } from '@kit.UserAuthenticationKit';
891
892let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
893let authType = userAuth.UserAuthType.FACE;
894let authTrustLevel = userAuth.AuthTrustLevel.ATL1;
895try {
896  let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
897  // Subscribe to the authentication result.
898  auth.on('result', {
899    callback: (result: userAuth.AuthResultInfo) => {
900      console.info(`authV9 result ${result.result}`);
901      console.info(`authV9 token ${result.token}`);
902      console.info(`authV9 remainAttempts ${result.remainAttempts}`);
903      console.info(`authV9 lockoutDuration ${result.lockoutDuration}`);
904    }
905  });
906  // Unsubscription result.
907  auth.off('result');
908  console.info('cancel subscribe authentication event success');
909} catch (error) {
910  console.error(`cancel subscribe authentication event failed, error = ${error}`);
911  // do error
912}
913```
914
915### start<sup>(deprecated)</sup>
916
917start : () => void
918
919Starts authentication.
920
921> **NOTE**<br>
922> - This API is supported since API version 9 and deprecated since API version 10.
923> - Use the [AuthInstance](#authinstancedeprecated) instance obtained to call this API.
924
925**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
926
927**System capability**: SystemCapability.UserIAM.UserAuth.Core
928
929**Error codes**
930
931For details about the error codes, see [User Authentication Error Codes](errorcode-useriam.md).
932
933| ID| Error Message|
934| -------- | ------- |
935| 201 | Permission verification failed. |
936| 401 | Incorrect parameters. |
937| 12500001 | Authentication failed. |
938| 12500002 | General operation error. |
939| 12500003 | The operation is canceled. |
940| 12500004 | The operation is time-out.  |
941| 12500005 | The authentication type is not supported. |
942| 12500006 | The authentication trust level is not supported. |
943| 12500007 | The authentication task is busy. |
944| 12500009 | The authenticator is locked. |
945| 12500010 | The type of credential has not been enrolled. |
946
947**Example**
948
949```ts
950import { userAuth } from '@kit.UserAuthenticationKit';
951
952let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
953let authType = userAuth.UserAuthType.FACE;
954let authTrustLevel = userAuth.AuthTrustLevel.ATL1;
955
956try {
957  let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
958  auth.start();
959  console.info('authV9 start auth success');
960} catch (error) {
961  console.error(`authV9 start auth failed, error = ${error}`);
962}
963```
964
965### cancel<sup>(deprecated)</sup>
966
967cancel : () => void
968
969Cancels this authentication.
970
971> **NOTE**<br>
972>
973> - This API is supported since API version 9 and deprecated since API version 10.
974> - Use the [AuthInstance](#authinstancedeprecated) instance obtained to invoke this API. The [AuthInstance](#authinstancedeprecated) instance must be the instance being authenticated.
975
976**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
977
978**System capability**: SystemCapability.UserIAM.UserAuth.Core
979
980**Error codes**
981
982For details about the error codes, see [User Authentication Error Codes](errorcode-useriam.md).
983
984| ID| Error Message|
985| -------- | ------- |
986| 201 | Permission verification failed. |
987| 401 | Incorrect parameters. |
988| 12500002 | General operation error. |
989
990**Example**
991
992```ts
993import { userAuth } from '@kit.UserAuthenticationKit';
994
995let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
996let authType = userAuth.UserAuthType.FACE;
997let authTrustLevel = userAuth.AuthTrustLevel.ATL1;
998
999try {
1000  let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
1001  auth.cancel();
1002  console.info('cancel auth success');
1003} catch (error) {
1004  console.error(`cancel auth failed, error = ${error}`);
1005}
1006```
1007
1008## userAuth.getAuthInstance<sup>(deprecated)</sup>
1009
1010getAuthInstance(challenge : Uint8Array, authType : UserAuthType, authTrustLevel : AuthTrustLevel): AuthInstance
1011
1012Obtains an **AuthInstance** instance for user authentication.
1013
1014> **NOTE**<br>
1015>
1016> - This API is supported since API version 9 and deprecated since API version 10. Use [getUserAuthInstance](#userauthgetuserauthinstance10) instead.
1017> - An **AuthInstance** instance can be used for an authentication only once.
1018
1019
1020**System capability**: SystemCapability.UserIAM.UserAuth.Core
1021
1022**Parameters**
1023
1024| Name        | Type                                    | Mandatory| Description                    |
1025| -------------- | ---------------------------------------- | ---- | ------------------------ |
1026| challenge      | Uint8Array                               | Yes  | Challenge value. It cannot exceed 32 bytes and can be passed in Uint8Array([]) format.|
1027| authType       | [UserAuthType](#userauthtype8)           | Yes  | Authentication type. Currently, **FACE** and **FINGERPRINT** are supported.|
1028| authTrustLevel | [AuthTrustLevel](#authtrustlevel8)       | Yes  | Authentication trust level.              |
1029
1030**Return value**
1031
1032| Type                                   | Description        |
1033| --------------------------------------- | ------------ |
1034| [AuthInstance](#authinstancedeprecated) | **AuthInstance** instance obtained.|
1035
1036**Error codes**
1037
1038For details about the error codes, see [User Authentication Error Codes](errorcode-useriam.md).
1039
1040| ID| Error Message|
1041| -------- | ------- |
1042| 401 | Incorrect parameters. |
1043| 12500002 | General operation error. |
1044| 12500005 | The authentication type is not supported. |
1045| 12500006 | The authentication trust level is not supported. |
1046
1047**Example**
1048
1049```ts
1050import { userAuth } from '@kit.UserAuthenticationKit';
1051
1052let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
1053let authType = userAuth.UserAuthType.FACE;
1054let authTrustLevel = userAuth.AuthTrustLevel.ATL1;
1055
1056try {
1057  let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
1058  console.info('let auth instance success');
1059} catch (error) {
1060  console.error(`get auth instance success failed, error = ${error}`);
1061}
1062```
1063
1064## userAuth.getAvailableStatus<sup>9+</sup>
1065
1066getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel): void
1067
1068Checks whether the specified authentication capability is supported.
1069
1070**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
1071
1072**Atomic service API**: This API can be used in atomic services since API version 12.
1073
1074**System capability**: SystemCapability.UserIAM.UserAuth.Core
1075
1076**Parameters**
1077
1078| Name        | Type                              | Mandatory| Description                      |
1079| -------------- | ---------------------------------- | ---- | -------------------------- |
1080| authType       | [UserAuthType](#userauthtype8)     | Yes  | Authentication type. PIN is supported since API version 11.|
1081| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes  | Authentication trust level.      |
1082
1083> The mechanism for returning the error code is as follows:
1084>
1085> - The error code 12500005 is returned if the corresponding executor is not registered.
1086> - The error code 12500006 is returned if the corresponding executor is registered, the function is not disabled, but the authentication security level is lower than that specified for the service.
1087> - The error code 12500010 is returned if the corresponding executor is registered, the function is not disabled, but the user has not enrolled the credential.
1088> - The error code 12500013 is returned if the corresponding executor is registered, the function is not disabled, but the PIN has expired.
1089
1090**Error codes**
1091
1092For details about the error codes, see [User Authentication Error Codes](errorcode-useriam.md).
1093
1094| ID| Error Message|
1095| -------- | ------- |
1096| 201 | Permission verification failed. |
1097| 401 | Incorrect parameters. Possible causes: 1.Mandatory parameters are left unspecified. |
1098| 12500002 | General operation error. |
1099| 12500005 | The authentication type is not supported. |
1100| 12500006 | The authentication trust level is not supported. |
1101| 12500010 | The type of credential has not been enrolled. |
1102| 12500013 | Operation failed because of PIN expired. |
1103
1104**Example**
1105
1106```ts
1107import { userAuth } from '@kit.UserAuthenticationKit';
1108
1109try {
1110  userAuth.getAvailableStatus(userAuth.UserAuthType.FACE, userAuth.AuthTrustLevel.ATL1);
1111  console.info('current auth trust level is supported');
1112} catch (error) {
1113  console.error(`current auth trust level is not supported, error = ${error}`);
1114}
1115```
1116
1117## UserAuthResultCode<sup>9+</sup>
1118
1119Enumerates the authentication result codes.
1120
1121**Atomic service API**: This API can be used in atomic services since API version 12.
1122
1123**System capability**: SystemCapability.UserIAM.UserAuth.Core
1124
1125| Name                   |   Value  | Description                |
1126| ----------------------- | ------ | -------------------- |
1127| SUCCESS                 | 12500000      | The authentication is successful.          |
1128| FAIL                    | 12500001      | The authentication failed.          |
1129| GENERAL_ERROR           | 12500002      | A general operation error occurred.      |
1130| CANCELED                | 12500003      | The authentication is canceled.          |
1131| TIMEOUT                 | 12500004      | The authentication timed out.          |
1132| TYPE_NOT_SUPPORT        | 12500005      | The authentication type is not supported.  |
1133| TRUST_LEVEL_NOT_SUPPORT | 12500006      | The authentication trust level is not supported.  |
1134| BUSY                    | 12500007      | Indicates the busy state.          |
1135| LOCKED                  | 12500009      | The authentication executor is locked.      |
1136| NOT_ENROLLED            | 12500010      | The user has not entered the authentication information.|
1137| CANCELED_FROM_WIDGET<sup>10+</sup> | 12500011 | The authentication is canceled by the user from the user authentication widget. If this error code is returned, the authentication is customized by the application.|
1138| PIN_EXPIRED<sup>12+</sup> | 12500013 | The authentication failed because the lock screen password has expired.|
1139
1140## UserAuth<sup>(deprecated)</sup>
1141
1142Provides APIs for user authentication.
1143
1144### constructor<sup>(deprecated)</sup>
1145
1146constructor()
1147
1148A constructor used to create a **UserAuth** instance.
1149
1150> **NOTE**<br>
1151> This API is supported since API version 8 and deprecated since API version 9. Use [getAuthInstance](#userauthgetauthinstancedeprecated) instead.
1152
1153**System capability**: SystemCapability.UserIAM.UserAuth.Core
1154
1155**Example**
1156
1157```ts
1158import { userAuth } from '@kit.UserAuthenticationKit';
1159
1160let auth = new userAuth.UserAuth();
1161```
1162
1163### getVersion<sup>(deprecated)</sup>
1164
1165getVersion() : number
1166
1167Obtains the version of this authenticator.
1168
1169> **NOTE**<br>
1170> This API is supported since API version 8 and deprecated since API version 9.
1171
1172**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
1173
1174**System capability**: SystemCapability.UserIAM.UserAuth.Core
1175
1176**Return value**
1177
1178| Type  | Description                  |
1179| ------ | ---------------------- |
1180| number | Authenticator version obtained.|
1181
1182**Example**
1183
1184```ts
1185import { userAuth } from '@kit.UserAuthenticationKit';
1186
1187let auth = new userAuth.UserAuth();
1188let version = auth.getVersion();
1189console.info(`auth version = ${version}`);
1190```
1191
1192### getAvailableStatus<sup>(deprecated)</sup>
1193
1194getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel) : number
1195
1196Checks whether the specified authentication capability is supported.
1197
1198> **NOTE**<br>
1199> This API is supported since API version 8 and deprecated since API version 9. Use [getAvailableStatus](#userauthgetavailablestatus9) instead.
1200
1201**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
1202
1203**System capability**: SystemCapability.UserIAM.UserAuth.Core
1204
1205**Parameters**
1206
1207| Name        | Type                              | Mandatory| Description                      |
1208| -------------- | ---------------------------------- | ---- | -------------------------- |
1209| authType       | [UserAuthType](#userauthtype8)     | Yes  | Authentication type. Currently, **FACE** and **FINGERPRINT** are supported.|
1210| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes  | Authentication trust level.      |
1211
1212**Return value**
1213
1214| Type  | Description                                                        |
1215| ------ | ------------------------------------------------------------ |
1216| number | Query result. If the authentication capability is supported, **SUCCESS** is returned. Otherwise, a [ResultCode](#resultcodedeprecated) is returned.|
1217
1218**Example**
1219
1220```ts
1221import { userAuth } from '@kit.UserAuthenticationKit';
1222
1223let auth = new userAuth.UserAuth();
1224let checkCode = auth.getAvailableStatus(userAuth.UserAuthType.FACE, userAuth.AuthTrustLevel.ATL1);
1225if (checkCode == userAuth.ResultCode.SUCCESS) {
1226  console.info('check auth support success');
1227} else {
1228  console.error(`check auth support fail, code = ${checkCode}`);
1229}
1230```
1231
1232### auth<sup>(deprecated)</sup>
1233
1234auth(challenge: Uint8Array, authType: UserAuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array
1235
1236Starts user authentication. This API uses a callback to return the result.
1237
1238> **NOTE**<br>
1239> This API is supported since API version 8 and deprecated since API version 9. Use [start](#startdeprecated) instead.
1240
1241**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
1242
1243**System capability**: SystemCapability.UserIAM.UserAuth.Core
1244
1245**Parameters**
1246
1247| Name        | Type                                    | Mandatory| Description                    |
1248| -------------- | ---------------------------------------- | ---- | ------------------------ |
1249| challenge      | Uint8Array                               | Yes  | Challenge value, which can be passed in Uint8Array([]) format.|
1250| authType       | [UserAuthType](#userauthtype8)           | Yes  | Authentication type. Currently, **FACE** and **FINGERPRINT** are supported.|
1251| authTrustLevel | [AuthTrustLevel](#authtrustlevel8)       | Yes  | Authentication trust level.            |
1252| callback       | [IUserAuthCallback](#iuserauthcallbackdeprecated) | Yes  | Callback used to return the result.       |
1253
1254**Return value**
1255
1256| Type      | Description                                                        |
1257| ---------- | ------------------------------------------------------------ |
1258| Uint8Array | Context ID, which is used as the input parameter of [cancelAuth](#cancelauthdeprecated).|
1259
1260**Example**
1261
1262```ts
1263import { userAuth } from '@kit.UserAuthenticationKit';
1264
1265let auth = new userAuth.UserAuth();
1266let challenge = new Uint8Array([]);
1267auth.auth(challenge, userAuth.UserAuthType.FACE, userAuth.AuthTrustLevel.ATL1, {
1268  onResult: (result, extraInfo) => {
1269    try {
1270      console.info(`auth onResult result = ${result}`);
1271      console.info(`auth onResult extraInfo = ${JSON.stringify(extraInfo)}`);
1272      if (result == userAuth.ResultCode.SUCCESS) {
1273        // Add the logic to be executed when the authentication is successful.
1274      } else {
1275        // Add the logic to be executed when the authentication fails.
1276      }
1277    } catch (error) {
1278      console.error(`auth onResult error = ${error}`);
1279    }
1280  }
1281});
1282```
1283
1284### cancelAuth<sup>(deprecated)</sup>
1285
1286cancelAuth(contextID : Uint8Array) : number
1287
1288Cancels an authentication based on the context ID.
1289
1290> **NOTE**<br>
1291> This API is supported since API version 8 and deprecated since API version 9. Use [cancel](#canceldeprecated) instead.
1292
1293**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
1294
1295**System capability**: SystemCapability.UserIAM.UserAuth.Core
1296
1297**Parameters**
1298
1299| Name   | Type      | Mandatory| Description                                      |
1300| --------- | ---------- | ---- | ------------------------------------------ |
1301| contextID | Uint8Array | Yes  | Context ID, which is obtained by [auth](#authdeprecated).|
1302
1303**Return value**
1304
1305| Type  | Description                    |
1306| ------ | ------------------------ |
1307| number | Returns **SUCCESS** if the cancellation is successful. Returns a [ResultCode](#resultcodedeprecated) otherwise.|
1308
1309**Example**
1310
1311```ts
1312import { userAuth } from '@kit.UserAuthenticationKit';
1313
1314// contextId can be obtained by auth(). In this example, it is defined here.
1315let contextId = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]);
1316let auth = new userAuth.UserAuth();
1317let cancelCode = auth.cancelAuth(contextId);
1318if (cancelCode == userAuth.ResultCode.SUCCESS) {
1319  console.info('cancel auth success');
1320} else {
1321  console.error('cancel auth fail');
1322}
1323```
1324
1325## IUserAuthCallback<sup>(deprecated)</sup>
1326
1327Provides callbacks to return the authentication result.
1328
1329> **NOTE**<br>
1330> This API is supported since API version 8 and deprecated since API version 9. Use [AuthEvent](#autheventdeprecated) instead.
1331
1332### onResult<sup>(deprecated)</sup>
1333
1334onResult: (result : number, extraInfo : AuthResult) => void
1335
1336Called to return the authentication result.
1337
1338> **NOTE**<br>
1339> This API is supported since API version 8 and deprecated since API version 9. Use [callback](#callbackdeprecated) instead.
1340
1341**System capability**: SystemCapability.UserIAM.UserAuth.Core
1342
1343**Parameters**
1344
1345| Name   | Type                      | Mandatory| Description       |
1346| --------- | -------------------------- | ---- | ------------------------------------------------ |
1347| result    | number           | Yes  | Authentication result. For details, see [ResultCode](#resultcodedeprecated).|
1348| extraInfo | [AuthResult](#authresultdeprecated) | Yes  | Extended information, which varies depending on the authentication result.<br>If the authentication is successful, the user authentication token will be returned in **extraInfo**.<br>If the authentication fails, the remaining number of authentication times will be returned in **extraInfo**.<br>If the authentication executor is locked, the freeze time will be returned in **extraInfo**.|
1349
1350**Example**
1351
1352```ts
1353import { userAuth } from '@kit.UserAuthenticationKit';
1354
1355let auth = new userAuth.UserAuth();
1356let challenge = new Uint8Array([]);
1357auth.auth(challenge, userAuth.UserAuthType.FACE, userAuth.AuthTrustLevel.ATL1, {
1358  onResult: (result, extraInfo) => {
1359    try {
1360      console.info(`auth onResult result = ${result}`);
1361      console.info(`auth onResult extraInfo = ${JSON.stringify(extraInfo)}`);
1362      if (result == userAuth.ResultCode.SUCCESS) {
1363        // Add the logic to be executed when the authentication is successful.
1364      }  else {
1365        // Add the logic to be executed when the authentication fails.
1366      }
1367    } catch (error) {
1368      console.error(`auth onResult error = ${error}`);
1369    }
1370  }
1371});
1372```
1373
1374### onAcquireInfo<sup>(deprecated)</sup>
1375
1376onAcquireInfo ?: (module : number, acquire : number, extraInfo : any) => void
1377
1378Called to acquire authentication tip information. This API is optional.
1379
1380> **NOTE**<br>
1381> This API is supported since API version 8 and deprecated since API version 9. Use [callback](#callbackdeprecated) instead.
1382
1383**System capability**: SystemCapability.UserIAM.UserAuth.Core
1384
1385**Parameters**
1386
1387| Name   | Type  | Mandatory| Description                          |
1388| --------- | ------ | ---- | ------------------------------ |
1389| module    | number | Yes  | ID of the module that sends the tip information.            |
1390| acquire   | number | Yes  | Authentication tip information.|
1391| extraInfo | any    | Yes  | Reserved field.                    |
1392
1393**Example**
1394
1395```ts
1396import { userAuth } from '@kit.UserAuthenticationKit';
1397
1398let auth = new userAuth.UserAuth();
1399let challenge = new Uint8Array([]);
1400auth.auth(challenge, userAuth.UserAuthType.FACE, userAuth.AuthTrustLevel.ATL1, {
1401  onResult: (result, extraInfo) => {
1402    try {
1403      console.info(`auth onResult result = ${result}`);
1404      console.info(`auth onResult extraInfo = ${JSON.stringify(extraInfo)}`);
1405      if (result == userAuth.ResultCode.SUCCESS) {
1406        // Add the logic to be executed when the authentication is successful.
1407      }  else {
1408        // Add the logic to be executed when the authentication fails.
1409      }
1410    } catch (error) {
1411      console.error(`auth onResult error = ${error}`);
1412    }
1413  },
1414  onAcquireInfo: (module, acquire, extraInfo : userAuth.AuthResult) => {
1415    try {
1416      console.info(`auth onAcquireInfo module = ${module}`);
1417      console.info(`auth onAcquireInfo acquire = ${acquire}`);
1418      console.info(`auth onAcquireInfo extraInfo = ${JSON.stringify(extraInfo)}`);
1419    } catch (error) {
1420      console.error(`auth onAcquireInfo error = ${error}`);
1421    }
1422  }
1423});
1424```
1425
1426## AuthResult<sup>(deprecated)</sup>
1427
1428Represents the authentication result object.
1429
1430> **NOTE**<br>
1431> This API is supported since API version 8 and deprecated since API version 9. Use [AuthResultInfo](#authresultinfodeprecated) instead.
1432
1433**System capability**: SystemCapability.UserIAM.UserAuth.Core
1434
1435| Name        | Type  | Mandatory| Description                |
1436| ------------ | ---------- | ---- | -------------------|
1437| token        | Uint8Array | No  | Authentication token information.|
1438| remainTimes  | number     | No  | Number of remaining authentication operations.|
1439| freezingTime | number     | No  | Time for which the authentication operation is frozen.|
1440
1441## ResultCode<sup>(deprecated)</sup>
1442
1443Enumerates the authentication result codes.
1444
1445> **NOTE**<br>
1446> This object is deprecated since API version 9. Use [UserAuthResultCode](#userauthresultcode9) instead.
1447
1448**System capability**: SystemCapability.UserIAM.UserAuth.Core
1449
1450| Name                   | Value| Description                |
1451| ----------------------- | ------ | -------------------- |
1452| SUCCESS                 | 0      | The operation is successful.          |
1453| FAIL                    | 1      | The authentication failed.          |
1454| GENERAL_ERROR           | 2      | A general operation error occurred.      |
1455| CANCELED                | 3      | The authentication is canceled.          |
1456| TIMEOUT                 | 4      | The authentication timed out.          |
1457| TYPE_NOT_SUPPORT        | 5      | The authentication type is not supported.  |
1458| TRUST_LEVEL_NOT_SUPPORT | 6      | The authentication trust level is not supported.  |
1459| BUSY                    | 7      | Indicates the busy state.          |
1460| INVALID_PARAMETERS      | 8      | Invalid parameters are detected.          |
1461| LOCKED                  | 9      | The authentication executor is locked.      |
1462| NOT_ENROLLED            | 10     | The user has not entered the authentication information.|
1463
1464## FaceTips<sup>(deprecated)</sup>
1465
1466Enumerates the tip codes used during the facial authentication process.
1467
1468> **NOTE**<br>
1469> This API is supported since API version 8 and deprecated since API version 11.
1470
1471**System capability**: SystemCapability.UserIAM.UserAuth.Core
1472
1473| Name                         |   Value  |    Description                            |
1474| ----------------------------- | ------ | ------------------------------------ |
1475| FACE_AUTH_TIP_TOO_BRIGHT      | 1      | The obtained facial image is too bright due to high illumination.          |
1476| FACE_AUTH_TIP_TOO_DARK        | 2      | The obtained facial image is too dark due to low illumination.          |
1477| FACE_AUTH_TIP_TOO_CLOSE       | 3      | The face is too close to the device.                  |
1478| FACE_AUTH_TIP_TOO_FAR         | 4      | The face is too far away from the device.                  |
1479| FACE_AUTH_TIP_TOO_HIGH        | 5      | Only the upper part of the face is captured because the device is angled too high.        |
1480| FACE_AUTH_TIP_TOO_LOW         | 6      | Only the lower part of the face is captured because the device is angled too low.        |
1481| FACE_AUTH_TIP_TOO_RIGHT       | 7      | Only the right part of the face is captured because the device is deviated to the right.      |
1482| FACE_AUTH_TIP_TOO_LEFT        | 8      | Only the left part of the face is captured because the device is deviated to the left.      |
1483| FACE_AUTH_TIP_TOO_MUCH_MOTION | 9      | The face moves too fast during facial information collection.|
1484| FACE_AUTH_TIP_POOR_GAZE       | 10     | The face is not facing the camera.                    |
1485| FACE_AUTH_TIP_NOT_DETECTED    | 11     | No face is detected.                |
1486
1487
1488## FingerprintTips<sup>(deprecated)</sup>
1489
1490Enumerates the tip codes used during the fingerprint authentication process.
1491
1492> **NOTE**<br>
1493> This API is supported since API version 8 and deprecated since API version 11.
1494
1495**System capability**: SystemCapability.UserIAM.UserAuth.Core
1496
1497| Name                             |   Value  | Description                                              |
1498| --------------------------------- | ------ | -------------------------------------------------- |
1499| FINGERPRINT_AUTH_TIP_GOOD         | 0      | The obtained fingerprint image is in good condition.                              |
1500| FINGERPRINT_AUTH_TIP_DIRTY        | 1      | Large fingerprint image noise is detected due to suspicious or detected dirt on the sensor.|
1501| FINGERPRINT_AUTH_TIP_INSUFFICIENT | 2      | The noise of the fingerprint image is too large to be processed.    |
1502| FINGERPRINT_AUTH_TIP_PARTIAL      | 3      | Incomplete fingerprint image is detected.                            |
1503| FINGERPRINT_AUTH_TIP_TOO_FAST     | 4      | The fingerprint image is incomplete due to fast movement.                        |
1504| FINGERPRINT_AUTH_TIP_TOO_SLOW     | 5      | Failed to obtain the fingerprint image because the finger seldom moves.                      |
1505
1506
1507## UserAuthType<sup>8+</sup>
1508
1509Enumerates the identity authentication types.
1510
1511**Atomic service API**: This API can be used in atomic services since API version 12.
1512
1513**System capability**: SystemCapability.UserIAM.UserAuth.Core
1514
1515| Name       | Value  | Description      |
1516| ----------- | ---- | ---------- |
1517| PIN<sup>10+</sup>         | 1    | PIN authentication.|
1518| FACE        | 2    | Facial authentication.|
1519| FINGERPRINT | 4    | Fingerprint authentication.|
1520
1521## AuthTrustLevel<sup>8+</sup>
1522
1523Enumerates the trust levels of the authentication result.
1524
1525**Atomic service API**: This API can be used in atomic services since API version 12.
1526
1527**System capability**: SystemCapability.UserIAM.UserAuth.Core
1528
1529| Name| Value   | Description                                                        |
1530| ---- | ----- | ------------------------------------------------------------ |
1531| ATL1 | 10000 | 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.|
1532| ATL2 | 20000 | 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.|
1533| ATL3 | 30000 | 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.|
1534| ATL4 | 40000 | 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.|
1535
1536## SecureLevel<sup>(deprecated)</sup>
1537
1538Enumerates the authentication security levels.
1539
1540> **NOTE**<br>This API is supported since API version 6 and deprecated since API version 8.
1541
1542**System capability**: SystemCapability.UserIAM.UserAuth.Core
1543
1544| Name| Value   | Description                                                        |
1545| ---- | ----- | ------------------------------------------------------------ |
1546| S1 | '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.|
1547| S2 | '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.|
1548| S3 | '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.|
1549| S4 | '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.|
1550
1551## AuthType<sup>(deprecated)</sup>
1552
1553Enumerates the authentication types.
1554
1555> **NOTE**<br>This API is supported since API version 6 and deprecated since API version 8.
1556
1557**System capability**: SystemCapability.UserIAM.UserAuth.Core
1558
1559| Name| Value   | Description                                                        |
1560| ---- | ----- | ------------------------------------------------------------ |
1561| ALL  | 'ALL' | A reserved parameter not supported by the current version.|
1562| FACE_ONLY | 'FACE_ONLY' | Facial authentication.|
1563
1564## userAuth.getAuthenticator<sup>(deprecated)</sup>
1565
1566getAuthenticator(): Authenticator
1567
1568Obtains an **Authenticator** instance for user authentication.
1569
1570> **NOTE**<br>
1571> This API is deprecated since API version 8. Use [constructor](#constructordeprecated) instead.
1572
1573**System capability**: SystemCapability.UserIAM.UserAuth.Core
1574
1575**Return value**
1576
1577| Type                                     | Description        |
1578| ----------------------------------------- | ------------ |
1579| [Authenticator](#authenticatordeprecated) | **Authenticator** instance obtained.|
1580
1581**Example**
1582  ```ts
1583  import { userAuth } from '@kit.UserAuthenticationKit';
1584
1585  let authenticator = userAuth.getAuthenticator();
1586  ```
1587
1588## Authenticator<sup>(deprecated)</sup>
1589
1590Defines the **Authenticator** object.
1591
1592> **NOTE**<br>
1593> This API is deprecated since API version 8. Use [UserAuth](#userauthdeprecated) instead.
1594
1595### execute<sup>(deprecated)</sup>
1596
1597execute(type: AuthType, level: SecureLevel, callback: AsyncCallback&lt;number&gt;): void
1598
1599Starts user authentication. This API uses an asynchronous callback to return the result.
1600
1601> **NOTE**<br>
1602> This API is deprecated since API version 8. Use [auth](#authdeprecated) instead.
1603
1604**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
1605
1606**System capability**: SystemCapability.UserIAM.UserAuth.Core
1607
1608**Parameters**
1609
1610| Name  | Type                       | Mandatory| Description                                                                                                                   |
1611| -------- | --------------------------- | ---- |-----------------------------------------------------------------------------------------------------------------------|
1612| type     | AuthType                      | Yes  | Authentication type. Currently, only **FACE_ONLY** is supported.<br>**ALL** is reserved and not supported by the current version.                                                                |
1613| level    | SecureLevel  | Yes  | Security level of the authentication. It can be **S1** (lowest), **S2**, **S3**, or **S4** (highest).<br>Devices capable of 3D facial recognition support S3 and lower-level authentication.<br>Devices capable of 2D facial recognition support S2 and lower-level authentication.|
1614| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the result. **number** indicates the [AuthenticationResult](#authenticationresultdeprecated).|
1615
1616**Example**
1617
1618```ts
1619import { userAuth } from '@kit.UserAuthenticationKit';
1620
1621let authenticator = userAuth.getAuthenticator();
1622authenticator.execute('FACE_ONLY', 'S2', (error, code)=>{
1623  if (code === userAuth.ResultCode.SUCCESS) {
1624    console.info('auth success');
1625    return;
1626  }
1627  console.error(`auth fail, code = ${code}`);
1628});
1629```
1630
1631
1632### execute<sup>(deprecated)</sup>
1633
1634execute(type : AuthType, level : SecureLevel): Promise&lt;number&gt;
1635
1636Starts user authentication. This API uses a promise to return the result.
1637
1638> **NOTE**<br>
1639> This API is deprecated since API version 8. Use [auth](#authdeprecated) instead.
1640
1641**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
1642
1643**System capability**: SystemCapability.UserIAM.UserAuth.Core
1644
1645**Parameters**
1646
1647| Name| Type  | Mandatory| Description                                                                                                                   |
1648| ------ | ------ | ---- |-----------------------------------------------------------------------------------------------------------------------|
1649| type   | AuthType | Yes  | Authentication type. Currently, only **FACE_ONLY** is supported.<br>**ALL** is reserved and not supported by the current version.                                                                |
1650| level  | SecureLevel | Yes  | Security level of the authentication. It can be **S1** (lowest), **S2**, **S3**, or **S4** (highest).<br>Devices capable of 3D facial recognition support S3 and lower-level authentication.<br>Devices capable of 2D facial recognition support S2 and lower-level authentication.|
1651
1652**Return value**
1653
1654| Type                 | Description                                                        |
1655| --------------------- | ------------------------------------------------------------ |
1656| Promise&lt;number&gt; | Promise used to return the authentication result, which is a number. For details, see [AuthenticationResult](#authenticationresultdeprecated).|
1657
1658**Example**
1659
1660```ts
1661import { userAuth } from '@kit.UserAuthenticationKit';
1662
1663try {
1664  let authenticator = userAuth.getAuthenticator();
1665  authenticator.execute('FACE_ONLY', 'S2').then((code)=>{
1666    console.info('auth success');
1667  })
1668} catch (error) {
1669  console.error(`auth fail, code = ${error}`);
1670}
1671```
1672
1673## AuthenticationResult<sup>(deprecated)</sup>
1674
1675Enumerates the authentication results.
1676
1677> **NOTE**<br>
1678> This object is deprecated since API version 8. Use [ResultCode](#resultcodedeprecated) instead.
1679
1680**System capability**: SystemCapability.UserIAM.UserAuth.Core
1681
1682| Name              |   Value  | Description                      |
1683| ------------------ | ------ | -------------------------- |
1684| NO_SUPPORT         | -1     | The device does not support the current authentication mode.|
1685| SUCCESS            | 0      | The authentication is successful.                |
1686| COMPARE_FAILURE    | 1      | The feature comparison failed.                |
1687| CANCELED           | 2      | The authentication was canceled by the user.            |
1688| TIMEOUT            | 3      | The authentication has timed out.                |
1689| CAMERA_FAIL        | 4      | The camera failed to start.            |
1690| BUSY               | 5      | The authentication service is not available. Try again later.  |
1691| INVALID_PARAMETERS | 6      | The authentication parameters are invalid.            |
1692| LOCKED             | 7      | The user account is locked because the number of authentication failures has reached the threshold.|
1693| NOT_ENROLLED       | 8      | No authentication credential is registered.          |
1694| GENERAL_ERROR      | 100    | Other errors.                |
1695