1# @ohos.userIAM.userAuth (用户认证)
2
3提供用户认证能力,可应用于设备解锁、支付、应用登录等身份认证场景。
4
5> **说明:**
6> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
7
8
9## 导入模块
10
11```ts
12import { userAuth } from '@kit.UserAuthenticationKit';
13```
14
15## 常量
16
17表示复用设备解锁结果最大有效时长。
18
19**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
20
21**系统能力**:SystemCapability.UserIAM.UserAuth.Core
22
23| 名称        | 值   | 说明       |
24| ----------- | ---- | ---------- |
25| MAX_ALLOWABLE_REUSE_DURATION<sup>12+</sup>    | 300000   | 复用设备解锁结果最大有效时长,值为300000毫秒。 |
26
27## EnrolledState<sup>12+</sup>
28
29表示用户注册凭据的状态。
30
31**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
32
33**系统能力**:SystemCapability.UserIAM.UserAuth.Core
34
35| 名称         | 类型    | 可读 | 可写 | 说明                 |
36| ------------ | ---------- | ---- | ---- | -------------------- |
37| credentialDigest       | number | 是   |  否 | 注册的凭据摘要,在凭据增加时随机生成。|
38| credentialCount        | number | 是   |  否 | 注册的凭据数量。       |
39
40## ReuseMode<sup>12+</sup>
41
42表示复用设备解锁结果的模式。
43
44**系统能力**:SystemCapability.UserIAM.UserAuth.Core
45
46| 名称        | 值   | 说明       |
47| ----------- | ---- | ---------- |
48| AUTH_TYPE_RELEVANT    | 1   | 与认证类型相关,只有当设备解锁结果在有效时间内,并且设备解锁的认证类型匹配上本次认证指定认证类型之一时,可以复用该结果。<br/> **原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
49| AUTH_TYPE_IRRELEVANT  | 2   | 与认证类型无关,只要解锁认证结果在有效时间内,就可以重复使用。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
50| CALLER_IRRELEVANT_AUTH_TYPE_RELEVANT<sup>14+</sup>    | 3   | 与认证类型相关,只有当任意身份认证(包括设备解锁)结果在有效时间内,并且身份认证的认证类型匹配上本次认证指定认证类型之一时,可以复用该结果。<br/>**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。 |
51| CALLER_IRRELEVANT_AUTH_TYPE_IRRELEVANT<sup>14+</sup>  | 4   | 与认证类型无关,只要任意身份认证(包括设备解锁)结果在有效时间内,就可以重复使用。<br/>**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。 |
52
53## ReuseUnlockResult<sup>12+</sup>
54
55表示复用设备解锁结果。
56> **说明**:
57>
58> 如果锁屏解锁后,在有效时间内凭据发生了变化,锁屏认证结果依然可以复用,认证结果中返回当前实际的EnrolledState。若复用锁屏认证结果
59> 时,凭据已经被完全删除,则返回的EnrolledState中credentialCount和credentialDigest均为0。
60
61**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
62
63**系统能力**:SystemCapability.UserIAM.UserAuth.Core
64
65| 名称         | 类型   | 必填 | 说明                 |
66| ------------ | ---------- | ---- | -------------------- |
67| reuseMode        | [ReuseMode](#reusemode12) | 是   | 复用设备解锁结果的模式。       |
68| reuseDuration    | number | 是   | 允许复用设备解锁结果的有效时长,有效时长的值应大于0,最大值为[MAX_ALLOWABLE_REUSE_DURATION](#常量)。 |
69
70## userAuth.getEnrolledState<sup>12+</sup>
71
72getEnrolledState(authType : UserAuthType): EnrolledState
73
74查询凭据注册的状态,用于感知用户注册凭据变化。
75
76**需要权限**:ohos.permission.ACCESS_BIOMETRIC
77
78**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
79
80**系统能力**:SystemCapability.UserIAM.UserAuth.Core
81
82**参数:**
83
84| 参数名         | 类型                               | 必填 | 说明                       |
85| -------------- | ---------------------------------- | ---- | -------------------------- |
86| authType       | [UserAuthType](#userauthtype8)     | 是   | 认证类型。|
87
88**返回值:**
89
90| 类型                  | 说明                                                         |
91| --------------------- | ------------------------------------------------------------ |
92| [EnrolledState](#enrolledstate12) | 当查询成功时,返回用户注册凭据的状态。 |
93
94**错误码:**
95
96以下错误码的详细介绍请参见[用户认证错误码](errorcode-useriam.md)。
97
98| 错误码ID | 错误信息 |
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**示例:**
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
121用户认证相关参数。
122
123**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
124
125**系统能力**:SystemCapability.UserIAM.UserAuth.Core
126
127| 名称           | 类型                               | 必填 | 说明                                                         |
128| -------------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
129| challenge      | Uint8Array                         | 是   | 随机挑战值,用来防重放攻击。最大长度为32字节,可传Uint8Array([])。 |
130| authType       | [UserAuthType](#userauthtype8)[]   | 是   | 认证类型列表,用来指定用户认证界面提供的认证方法。           |
131| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | 是   | 认证信任等级。                                               |
132| reuseUnlockResult<sup>12+</sup> | [ReuseUnlockResult](#reuseunlockresult12) | 否   |表示可以复用设备解锁结果。|
133
134## WidgetParam<sup>10+</sup>
135
136用户认证界面配置相关参数。
137
138**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
139
140**系统能力**:SystemCapability.UserIAM.UserAuth.Core
141
142| 名称                 | 类型                                | 必填 | 说明                                                         |
143| -------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ |
144| title                | string                              | 是   | 用户认证界面的标题,最大长度为500字符。                      |
145| navigationButtonText | string                              | 否   | 导航按键的说明文本,最大长度为60字符。仅在单指纹、单人脸场景下支持。 |
146
147## UserAuthResult<sup>10+</sup>
148
149用户认证结果。当认证结果为成功时,返回认证类型和认证通过的令牌信息。
150
151**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
152
153**系统能力**:SystemCapability.UserIAM.UserAuth.Core
154
155| 名称     | 类型                           | 必填 | 说明                                                         |
156| -------- | ------------------------------ | ---- | ------------------------------------------------------------ |
157| result   | number                         | 是   | 用户认证结果。若成功返回SUCCESS,若失败返回相应错误码,参见[UserAuthResultCode](#userauthresultcode9)。 |
158| token    | Uint8Array                     | 否   | 当认证结果为成功时,返回认证通过的令牌信息。                 |
159| authType | [UserAuthType](#userauthtype8) | 否   | 当认证结果为成功时,返回认证类型。                           |
160| enrolledState<sup>12+</sup> | [EnrolledState](#enrolledstate12) | 否   |  当认证结果为成功时,返回注册凭据的状态。         |
161
162## IAuthCallback<sup>10+</sup>
163
164返回认证结果的回调对象。
165
166### onResult<sup>10+</sup>
167
168onResult(result: UserAuthResult): void
169
170回调函数,返回认证结果。如果认证成功,可以通过UserAuthResult获取到认证通过的令牌信息。
171
172**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
173
174**系统能力**:SystemCapability.UserIAM.UserAuth.Core
175
176**参数:**
177
178| 参数名 | 类型                                | 必填 | 说明       |
179| ------ | ----------------------------------- | ---- | ---------- |
180| result | [UserAuthResult](#userauthresult10) | 是   | 认证结果。 |
181
182**示例1:**
183
184发起用户认证,采用认证可信等级≥ATL3的人脸+锁屏密码认证,获取认证结果:
185
186```ts
187import { BusinessError } from '@kit.BasicServicesKit';
188import { cryptoFramework } from '@kit.CryptoArchitectureKit';
189import { userAuth } from '@kit.UserAuthenticationKit';
190
191try {
192  const rand = cryptoFramework.createRandom();
193  const len: number = 16;
194  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
195  const authParam: userAuth.AuthParam = {
196    challenge: randData,
197    authType: [userAuth.UserAuthType.PIN],
198    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
199  };
200  const widgetParam: userAuth.WidgetParam = {
201    title: '请输入密码',
202  };
203
204  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
205  console.info('get userAuth instance success');
206  // 需要调用UserAuthInstance的start()接口,启动认证后,才能通过onResult获取到认证结果。
207  userAuthInstance.on('result', {
208    onResult (result) {
209      console.info(`userAuthInstance callback result = ${JSON.stringify(result)}`);
210    }
211  });
212  console.info('auth on success');
213} catch (error) {
214  const err: BusinessError = error as BusinessError;
215  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
216}
217```
218
219**示例2:**
220
221发起用户认证,采用认证可信等级≥ATL3的人脸 + 认证类型相关 + 复用设备解锁最大有效时长认证,获取认证结果:
222
223```ts
224import { BusinessError } from '@kit.BasicServicesKit';
225import { cryptoFramework } from '@kit.CryptoArchitectureKit';
226import { userAuth } from '@kit.UserAuthenticationKit';
227
228let reuseUnlockResult: userAuth.ReuseUnlockResult = {
229  reuseMode: userAuth.ReuseMode.AUTH_TYPE_RELEVANT,
230  reuseDuration: userAuth.MAX_ALLOWABLE_REUSE_DURATION,
231}
232try {
233  const rand = cryptoFramework.createRandom();
234  const len: number = 16;
235  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
236  const authParam: userAuth.AuthParam = {
237    challenge: randData,
238    authType: [userAuth.UserAuthType.PIN],
239    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
240    reuseUnlockResult: reuseUnlockResult,
241  };
242  const widgetParam: userAuth.WidgetParam = {
243    title: '请输入密码',
244  };
245  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
246  console.info('get userAuth instance success');
247  // 需要调用UserAuthInstance的start()接口,启动认证后,才能通过onResult获取到认证结果。
248  userAuthInstance.on('result', {
249    onResult (result) {
250      console.info(`userAuthInstance callback result = ${JSON.stringify(result)}`);
251    }
252  });
253  console.info('auth on success');
254} catch (error) {
255  const err: BusinessError = error as BusinessError;
256  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
257}
258```
259
260**示例3:**
261
262发起用户认证,采用认证可信等级≥ATL3的人脸 + 任意应用认证类型相关 + 复用任意应用最大有效时长认证,获取认证结果:
263
264```ts
265import { BusinessError } from '@kit.BasicServicesKit';
266import { cryptoFramework } from '@kit.CryptoArchitectureKit';
267import { userAuth } from '@kit.UserAuthenticationKit';
268
269let reuseUnlockResult: userAuth.ReuseUnlockResult = {
270  reuseMode: userAuth.ReuseMode.CALLER_IRRELEVANT_AUTH_TYPE_RELEVANT,
271  reuseDuration: userAuth.MAX_ALLOWABLE_REUSE_DURATION,
272}
273try {
274  const rand = cryptoFramework.createRandom();
275  const len: number = 16;
276  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
277  const authParam: userAuth.AuthParam = {
278    challenge: randData,
279    authType: [userAuth.UserAuthType.PIN],
280    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
281    reuseUnlockResult: reuseUnlockResult,
282  };
283  const widgetParam: userAuth.WidgetParam = {
284    title: '请输入密码',
285  };
286  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
287  console.info('get userAuth instance success');
288  // 需要调用UserAuthInstance的start()接口,启动认证后,才能通过onResult获取到认证结果。
289  userAuthInstance.on('result', {
290    onResult (result) {
291      console.info(`userAuthInstance callback result = ${JSON.stringify(result)}`);
292    }
293  });
294  console.info('auth on success');
295} catch (error) {
296  const err: BusinessError = error as BusinessError;
297  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
298}
299```
300
301## UserAuthInstance<sup>10+</sup>
302
303用于执行用户身份认证,并支持使用统一用户身份认证控件。
304使用以下接口前,都需要先通过[getUserAuthInstance](#userauthgetuserauthinstance10)方法获取UserAuthInstance对象。
305
306### on<sup>10+</sup>
307
308on(type: 'result', callback: IAuthCallback): void
309
310订阅用户身份认证结果。
311
312**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
313
314**系统能力**:SystemCapability.UserIAM.UserAuth.Core
315
316**参数:**
317
318| 参数名   | 类型                              | 必填 | 说明                                       |
319| -------- | --------------------------------- | ---- | ------------------------------------------ |
320| type     | 'result'                          | 是   | 订阅事件类型,表明该事件用来返回认证结果。 |
321| callback | [IAuthCallback](#iauthcallback10) | 是   | 认证接口的回调函数,用于返回认证结果。     |
322
323**错误码:**
324
325以下错误码的详细介绍请参见[用户认证错误码](errorcode-useriam.md)。
326
327| 错误码ID | 错误信息                 |
328| -------- | ------------------------ |
329| 401      | Incorrect parameters. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
330| 12500002 | General operation error. |
331
332**示例:**
333
334```ts
335import { BusinessError } from '@kit.BasicServicesKit';
336import { cryptoFramework } from '@kit.CryptoArchitectureKit';
337import { userAuth } from '@kit.UserAuthenticationKit';
338
339try {
340  const rand = cryptoFramework.createRandom();
341  const len: number = 16;
342  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
343  const authParam: userAuth.AuthParam = {
344    challenge: randData,
345    authType: [userAuth.UserAuthType.PIN],
346    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
347  };
348  const widgetParam: userAuth.WidgetParam = {
349    title: '请输入密码',
350  };
351  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
352  console.info('get userAuth instance success');
353  // 需要调用UserAuthInstance的start()接口,启动认证后,才能通过onResult获取到认证结果。
354  userAuthInstance.on('result', {
355    onResult (result) {
356      console.info(`userAuthInstance callback result = ${JSON.stringify(result)}`);
357    }
358  });
359  console.info('auth on success');
360} catch (error) {
361  const err: BusinessError = error as BusinessError;
362  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
363}
364```
365
366### off<sup>10+</sup>
367
368off(type: 'result', callback?: IAuthCallback): void
369
370取消订阅用户身份认证结果。
371
372> **说明**:
373>
374> 需要使用已经成功订阅事件的[UserAuthInstance](#userauthinstance10)对象调用该接口进行取消订阅。
375
376**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
377
378**系统能力**:SystemCapability.UserIAM.UserAuth.Core
379
380**参数:**
381
382| 参数名   | 类型                              | 必填 | 说明                                       |
383| -------- | --------------------------------- | ---- | ------------------------------------------ |
384| type     | 'result'                          | 是   | 订阅事件类型,表明该事件用来返回认证结果。 |
385| callback | [IAuthCallback](#iauthcallback10) | 否   | 认证接口的回调函数,用于返回认证结果。     |
386
387**错误码:**
388
389以下错误码的详细介绍请参见[用户认证错误码](errorcode-useriam.md)。
390
391| 错误码ID | 错误信息                 |
392| -------- | ------------------------ |
393| 401      | Incorrect parameters. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
394| 12500002 | General operation error. |
395
396**示例:**
397
398```ts
399import { BusinessError } from '@kit.BasicServicesKit';
400import { cryptoFramework } from '@kit.CryptoArchitectureKit';
401import { userAuth } from '@kit.UserAuthenticationKit';
402
403try {
404  const rand = cryptoFramework.createRandom();
405  const len: number = 16;
406  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
407  const authParam: userAuth.AuthParam = {
408    challenge: randData,
409    authType: [userAuth.UserAuthType.PIN],
410    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
411  };
412  const widgetParam: userAuth.WidgetParam = {
413    title: '请输入密码',
414  };
415  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
416  console.info('get userAuth instance success');
417  userAuthInstance.off('result', {
418    onResult (result) {
419      console.info(`auth off result = ${JSON.stringify(result)}`);
420    }
421  });
422  console.info('auth off success');
423} catch (error) {
424  const err: BusinessError = error as BusinessError;
425  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
426}
427```
428
429### start<sup>10+</sup>
430
431start(): void
432
433开始认证。
434
435> **说明:**
436> 每个UserAuthInstance只能进行一次认证,若需要再次进行认证则需重新获取UserAuthInstance。
437
438**需要权限**:ohos.permission.ACCESS_BIOMETRIC
439
440**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
441
442**系统能力**:SystemCapability.UserIAM.UserAuth.Core
443
444**错误码:**
445
446以下错误码的详细介绍请参见[用户认证错误码](errorcode-useriam.md)。
447
448| 错误码ID | 错误信息                                         |
449| -------- | ------------------------------------------------ |
450| 201      | Permission verification failed.                  |
451| 401      | Incorrect parameters. Possible causes: 1.Incorrect parameter types. |
452| 12500001 | Authentication failed.                           |
453| 12500002 | General operation error.                         |
454| 12500003 | Authentication canceled.                         |
455| 12500004 | Authentication timeout.                          |
456| 12500005 | The authentication type is not supported.        |
457| 12500006 | The authentication trust level is not supported. |
458| 12500007 | Authentication service is busy.                  |
459| 12500009 | Authentication is locked out.                    |
460| 12500010 | The type of credential has not been enrolled.    |
461| 12500011 | Switched to the custom authentication process.   |
462| 12500013 | Operation failed because of PIN expired. |
463
464**示例:**
465
466```ts
467import { BusinessError } from '@kit.BasicServicesKit';
468import { cryptoFramework } from '@kit.CryptoArchitectureKit';
469import { userAuth } from '@kit.UserAuthenticationKit';
470
471try {
472  const rand = cryptoFramework.createRandom();
473  const len: number = 16;
474  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
475  const authParam: userAuth.AuthParam = {
476    challenge: randData,
477    authType: [userAuth.UserAuthType.PIN],
478    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
479  };
480  const widgetParam: userAuth.WidgetParam = {
481    title: '请输入密码',
482  };
483  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
484  console.info('get userAuth instance success');
485  userAuthInstance.start();
486  console.info('auth start success');
487} catch (error) {
488  const err: BusinessError = error as BusinessError;
489  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
490}
491```
492
493### cancel<sup>10+</sup>
494
495cancel(): void
496
497取消认证。
498
499> **说明**:
500>
501> 此时UserAuthInstance需要是正在进行认证的对象。
502
503**需要权限**:ohos.permission.ACCESS_BIOMETRIC
504
505**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
506
507**系统能力**:SystemCapability.UserIAM.UserAuth.Core
508
509**错误码:**
510
511| 错误码ID | 错误信息                        |
512| -------- | ------------------------------- |
513| 201      | Permission verification failed. |
514| 401      | Incorrect parameters. Possible causes: 1.Incorrect parameter types. |
515| 12500002 | General operation error.        |
516
517**示例:**
518
519```ts
520import { BusinessError } from '@kit.BasicServicesKit';
521import { cryptoFramework } from '@kit.CryptoArchitectureKit';
522import { userAuth } from '@kit.UserAuthenticationKit';
523
524try {
525  const rand = cryptoFramework.createRandom();
526  const len: number = 16;
527  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
528  const authParam : userAuth.AuthParam = {
529    challenge: randData,
530    authType: [userAuth.UserAuthType.PIN],
531    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
532  };
533  const widgetParam: userAuth.WidgetParam = {
534    title: '请输入密码',
535  };
536  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
537  console.info('get userAuth instance success');
538  // 需要调用UserAuthInstance的start()接口,启动认证后,才能调用cancel()接口。
539  userAuthInstance.cancel();
540  console.info('auth cancel success');
541} catch (error) {
542  const err: BusinessError = error as BusinessError;
543  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
544}
545```
546
547## userAuth.getUserAuthInstance<sup>10+</sup>
548
549getUserAuthInstance(authParam: AuthParam, widgetParam: WidgetParam): UserAuthInstance
550
551获取[UserAuthInstance](#userauthinstance10)对象,用于执行用户身份认证,并支持使用统一用户身份认证控件。
552
553> **说明:**
554> 每个UserAuthInstance只能进行一次认证,若需要再次进行认证则需重新获取UserAuthInstance。
555
556**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
557
558**系统能力**:SystemCapability.UserIAM.UserAuth.Core
559
560**参数:**
561
562| 参数名      | 类型                          | 必填 | 说明                       |
563| ----------- | ----------------------------- | ---- | -------------------------- |
564| authParam   | [AuthParam](#authparam10)      | 是   | 用户认证相关参数。         |
565| widgetParam | [WidgetParam](#widgetparam10) | 是   | 用户认证界面配置相关参数。 |
566
567**返回值:**
568
569| 类型                                    | 说明                       |
570| --------------------------------------- | -------------------------- |
571| [UserAuthInstance](#userauthinstance10) | 支持用户界面的认证器对象。 |
572
573**错误码:**
574
575以下错误码的详细介绍请参见[用户认证错误码](errorcode-useriam.md)。
576
577| 错误码ID | 错误信息                                         |
578| -------- | ------------------------------------------------ |
579| 401      | Incorrect parameters. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.   |
580| 12500002 | General operation error.                         |
581| 12500005 | The authentication type is not supported.        |
582| 12500006 | The authentication trust level is not supported. |
583
584**示例:**
585
586```ts
587import { BusinessError } from '@kit.BasicServicesKit';
588import { cryptoFramework } from '@kit.CryptoArchitectureKit';
589import { userAuth } from '@kit.UserAuthenticationKit';
590
591try {
592  const rand = cryptoFramework.createRandom();
593  const len: number = 16;
594  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
595  const authParam: userAuth.AuthParam = {
596    challenge: randData,
597    authType: [userAuth.UserAuthType.PIN],
598    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
599  };
600  const widgetParam: userAuth.WidgetParam = {
601    title: '请输入密码',
602  };
603  let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
604  console.info('get userAuth instance success');
605} catch (error) {
606  const err: BusinessError = error as BusinessError;
607  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
608}
609```
610
611## AuthResultInfo<sup>(deprecated)</sup>
612
613表示认证结果信息。
614
615> **说明:**
616> 从 API version 9 开始支持,从 API version 11 开始废弃。
617
618**系统能力**:SystemCapability.UserIAM.UserAuth.Core
619
620| 名称         | 类型   | 必填 | 说明                 |
621| ------------ | ---------- | ---- | -------------------- |
622| result        | number | 是   | 认证结果。       |
623| token        | Uint8Array | 否   | 用户身份认证通过的凭证。 |
624| remainAttempts  | number     | 否   | 剩余的认证尝试次数。 |
625| lockoutDuration | number     | 否   | 认证操作的锁定时长,时间单位为毫秒ms。 |
626
627## TipInfo<sup>(deprecated)</sup>
628
629表示认证过程中的提示信息。
630
631> **说明:**
632> 从 API version 9 开始支持,从 API version 11 开始废弃。
633
634**系统能力**:SystemCapability.UserIAM.UserAuth.Core635
636| 名称         | 类型   | 必填 | 说明                 |
637| ------------ | ---------- | ---- | -------------------- |
638| module        | number | 是   | 发送提示信息的模块标识。       |
639| tip        | number | 是   | 认证过程提示信息。       |
640
641## EventInfo<sup>(deprecated)</sup>
642
643type EventInfo = AuthResultInfo | TipInfo
644
645表示认证过程中事件信息的类型。
646
647该类型为下表类型中的联合类型。
648
649> **说明:**
650> 从 API version 9 开始支持,从 API version 11 开始废弃,请使用[UserAuthResult](#userauthresult10)替代。
651
652**系统能力**:SystemCapability.UserIAM.UserAuth.Core653
654| 类型    | 说明                       |
655| --------- | ----------------------- |
656| [AuthResultInfo](#authresultinfodeprecated)    | 获取到的认证结果信息。  |
657| [TipInfo](#tipinfodeprecated)    | 认证过程中的提示信息。      |
658
659## AuthEventKey<sup>(deprecated)</sup>
660
661type AuthEventKey = 'result' | 'tip'
662
663表示认证事件类型的关键字,作为[on](#ondeprecated)接口的的参数。
664
665该类型为下表类型取值中的联合类型。
666
667> **说明:**
668> 从 API version 9 开始支持,从 API version 11 开始废弃。
669
670**系统能力**:SystemCapability.UserIAM.UserAuth.Core671
672| 类型       | 说明                    |
673| ---------- | ----------------------- |
674| 'result' | [on](#ondeprecated)接口第一个参数为"result"时,[callback](#callbackdeprecated)回调返回认证的结果信息。 |
675| 'tip'    | [on](#ondeprecated)接口第一个参数为"tip"时,[callback](#callbackdeprecated)回调返回认证操作中的提示信息。 |
676
677## AuthEvent<sup>(deprecated)</sup>
678
679认证接口的异步回调对象。
680
681> **说明:**
682> 从 API version 9 开始支持,从 API version 11 开始废弃,请使用[IAuthCallback](#iauthcallback10)替代。
683
684### callback<sup>(deprecated)</sup>
685
686callback(result : EventInfo) : void
687
688通过该回调获取认证结果信息或认证过程中的提示信息。
689
690> **说明:**
691> 从 API version 9 开始支持,从 API version 11 开始废弃,请使用[onResult](#onresult10)替代。
692
693**系统能力**:SystemCapability.UserIAM.UserAuth.Core
694
695**参数:**
696
697| 参数名    | 类型                       | 必填 | 说明                           |
698| --------- | -------------------------- | ---- | ------------------------------ |
699| result    | [EventInfo](#eventinfodeprecated)     | 是   | 返回的认证结果信息或提示信息。  |
700
701**示例:**
702
703```ts
704import { userAuth } from '@kit.UserAuthenticationKit';
705
706let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
707let authType = userAuth.UserAuthType.FACE;
708let authTrustLevel = userAuth.AuthTrustLevel.ATL1;
709// 通过callback获取认证结果
710try {
711  let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
712  auth.on('result', {
713    callback: (result: userAuth.AuthResultInfo) => {
714      console.info(`authV9 result ${result.result}`);
715      console.info(`authV9 token ${result.token}`);
716      console.info(`authV9 remainAttempts ${result.remainAttempts}`);
717      console.info(`authV9 lockoutDuration ${result.lockoutDuration}`);
718    }
719  } as userAuth.AuthEvent);
720  auth.start();
721  console.info('authV9 start success');
722} catch (error) {
723  console.error(`authV9 error = ${error}`);
724  // do error
725}
726// 通过callback获取认证过程中的提示信息
727try {
728  let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
729  auth.on('tip', {
730    callback : (result : userAuth.TipInfo) => {
731      switch (result.tip) {
732        case userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT:
733          // do something;
734        case userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK:
735          // do something;
736        default:
737          // do others
738      }
739    }
740  } as userAuth.AuthEvent);
741  auth.start();
742  console.info('authV9 start success');
743} catch (error) {
744  console.error(`authV9 error = ${error}`);
745  // do error
746}
747```
748
749## AuthInstance<sup>(deprecated)</sup>
750
751执行用户认证的对象。
752
753> **说明:**
754> 从 API version 9 开始支持,从 API version 10 开始废弃,请使用[UserAuthInstance](#userauthinstance10)替代。
755
756### on<sup>(deprecated)</sup>
757
758on : (name : AuthEventKey, callback : AuthEvent) => void
759
760订阅指定类型的用户认证事件。
761
762> **说明:**
763> - 从 API version 9 开始支持,从 API version 10 开始废弃。
764> - 使用获取到的[AuthInstance](#authinstancedeprecated)对象调用该接口进行订阅。
765
766**系统能力**:SystemCapability.UserIAM.UserAuth.Core
767
768**参数:**
769
770| 参数名    | 类型                        | 必填 | 说明                       |
771| --------- | -------------------------- | ---- | ------------------------- |
772| name  | [AuthEventKey](#autheventkeydeprecated) | 是   | 表示认证事件类型,取值为"result"时,回调函数返回认证结果;取值为"tip"时,回调函数返回认证过程中的提示信息。 |
773| callback  | [AuthEvent](#autheventdeprecated)   | 是   | 认证接口的回调函数,用于返回认证结果或认证过程中的提示信息。 |
774
775**错误码:**
776
777以下错误码的详细介绍请参见[用户认证错误码](errorcode-useriam.md)。
778
779| 错误码ID | 错误信息 |
780| -------- | ------- |
781| 401 | Incorrect parameters. |
782| 12500002 | General operation error. |
783
784**示例:**
785
786```ts
787import { userAuth } from '@kit.UserAuthenticationKit';
788
789let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
790let authType = userAuth.UserAuthType.FACE;
791let authTrustLevel = userAuth.AuthTrustLevel.ATL1;
792try {
793  let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
794  // 订阅认证结果
795  auth.on('result', {
796    callback: (result: userAuth.AuthResultInfo) => {
797      console.info(`authV9 result ${result.result}`);
798      console.info(`authV9 token ${result.token}`);
799      console.info(`authV9 remainAttempts ${result.remainAttempts}`);
800      console.info(`authV9 lockoutDuration ${result.lockoutDuration}`);
801    }
802  });
803  // 订阅认证过程中的提示信息
804  auth.on('tip', {
805    callback : (result : userAuth.TipInfo) => {
806      switch (result.tip) {
807        case userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT:
808          // do something;
809        case userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK:
810          // do something;
811        default:
812          // do others
813      }
814    }
815  } as userAuth.AuthEvent);
816  auth.start();
817  console.info('authV9 start success');
818} catch (error) {
819  console.error(`authV9 error = ${error}`);
820  // do error
821}
822```
823
824### off<sup>(deprecated)</sup>
825
826off : (name : AuthEventKey) => void
827
828取消订阅特定类型的认证事件。
829
830> **说明:**
831> - 从 API version 9 开始支持,从 API version 10 开始废弃。
832> - 需要使用已经成功订阅事件的[AuthInstance](#authinstancedeprecated)对象调用该接口进行取消订阅。
833
834**系统能力**:SystemCapability.UserIAM.UserAuth.Core
835
836| 名称    | 类型                        | 必填 | 说明                       |
837| --------- | -------------------------- | ---- | ------------------------- |
838| name    | [AuthEventKey](#autheventkeydeprecated)      | 是   | 表示认证事件类型,取值为"result"时,取消订阅认证结果;取值为"tip"时,取消订阅认证过程中的提示信息。 |
839
840**错误码:**
841
842以下错误码的详细介绍请参见[用户认证错误码](errorcode-useriam.md)。
843
844| 错误码ID | 错误信息 |
845| -------- | ------- |
846| 401 | Incorrect parameters. |
847| 12500002 | General operation error. |
848
849**示例:**
850
851```ts
852import { userAuth } from '@kit.UserAuthenticationKit';
853
854let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
855let authType = userAuth.UserAuthType.FACE;
856let authTrustLevel = userAuth.AuthTrustLevel.ATL1;
857try {
858  let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
859  // 订阅认证结果
860  auth.on('result', {
861    callback: (result: userAuth.AuthResultInfo) => {
862      console.info(`authV9 result ${result.result}`);
863      console.info(`authV9 token ${result.token}`);
864      console.info(`authV9 remainAttempts ${result.remainAttempts}`);
865      console.info(`authV9 lockoutDuration ${result.lockoutDuration}`);
866    }
867  });
868  // 取消订阅结果
869  auth.off('result');
870  console.info('cancel subscribe authentication event success');
871} catch (error) {
872  console.error(`cancel subscribe authentication event failed, error = ${error}`);
873  // do error
874}
875```
876
877### start<sup>(deprecated)</sup>
878
879start : () => void
880
881开始认证。
882
883> **说明:**
884> - 从 API version 9 开始支持,从 API version 10 开始废弃。
885> - 使用获取到的[AuthInstance](#authinstancedeprecated)对象调用该接口进行认证。
886
887**需要权限**:ohos.permission.ACCESS_BIOMETRIC
888
889**系统能力**:SystemCapability.UserIAM.UserAuth.Core
890
891**错误码:**
892
893以下错误码的详细介绍请参见[用户认证错误码](errorcode-useriam.md)。
894
895| 错误码ID | 错误信息 |
896| -------- | ------- |
897| 201 | Permission verification failed. |
898| 401 | Incorrect parameters. |
899| 12500001 | Authentication failed. |
900| 12500002 | General operation error. |
901| 12500003 | The operation is canceled. |
902| 12500004 | The operation is time-out.  |
903| 12500005 | The authentication type is not supported. |
904| 12500006 | The authentication trust level is not supported. |
905| 12500007 | The authentication task is busy. |
906| 12500009 | The authenticator is locked. |
907| 12500010 | The type of credential has not been enrolled. |
908
909**示例:**
910
911```ts
912import { userAuth } from '@kit.UserAuthenticationKit';
913
914let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
915let authType = userAuth.UserAuthType.FACE;
916let authTrustLevel = userAuth.AuthTrustLevel.ATL1;
917
918try {
919  let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
920  auth.start();
921  console.info('authV9 start auth success');
922} catch (error) {
923  console.error(`authV9 start auth failed, error = ${error}`);
924}
925```
926
927### cancel<sup>(deprecated)</sup>
928
929cancel : () => void
930
931取消认证。
932
933> **说明:**
934>
935> - 从 API version 9 开始支持,从 API version 10 开始废弃。
936> - 使用获取到的[AuthInstance](#authinstancedeprecated)对象调用该接口进行取消认证,此[AuthInstance](#authinstancedeprecated)需要是正在进行认证的对象。
937
938**需要权限**:ohos.permission.ACCESS_BIOMETRIC
939
940**系统能力**:SystemCapability.UserIAM.UserAuth.Core
941
942**错误码:**
943
944以下错误码的详细介绍请参见[用户认证错误码](errorcode-useriam.md)。
945
946| 错误码ID | 错误信息 |
947| -------- | ------- |
948| 201 | Permission verification failed. |
949| 401 | Incorrect parameters. |
950| 12500002 | General operation error. |
951
952**示例:**
953
954```ts
955import { userAuth } from '@kit.UserAuthenticationKit';
956
957let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
958let authType = userAuth.UserAuthType.FACE;
959let authTrustLevel = userAuth.AuthTrustLevel.ATL1;
960
961try {
962  let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
963  auth.cancel();
964  console.info('cancel auth success');
965} catch (error) {
966  console.error(`cancel auth failed, error = ${error}`);
967}
968```
969
970## userAuth.getAuthInstance<sup>(deprecated)</sup>
971
972getAuthInstance(challenge : Uint8Array, authType : UserAuthType, authTrustLevel : AuthTrustLevel): AuthInstance
973
974获取AuthInstance对象,用于执行用户身份认证。
975
976> **说明:**
977>
978> - 从 API version 9 开始支持,从 API version 10 开始废弃,请使用[getUserAuthInstance](#userauthgetuserauthinstance10)替代。
979> - 每个AuthInstance只能进行一次认证,若需要再次进行认证则需重新获取AuthInstance。
980
981
982**系统能力**:SystemCapability.UserIAM.UserAuth.Core
983
984**参数:**
985
986| 参数名         | 类型                                     | 必填 | 说明                     |
987| -------------- | ---------------------------------------- | ---- | ------------------------ |
988| challenge      | Uint8Array                               | 是   | 挑战值,最大长度为32字节,可以传Uint8Array([])。 |
989| authType       | [UserAuthType](#userauthtype8)           | 是   | 认证类型,当前支持FACE和FINGERPRINT。 |
990| authTrustLevel | [AuthTrustLevel](#authtrustlevel8)       | 是   | 认证信任等级。               |
991
992**返回值:**
993
994| 类型                                    | 说明         |
995| --------------------------------------- | ------------ |
996| [AuthInstance](#authinstancedeprecated) | 认证器对象。 |
997
998**错误码:**
999
1000以下错误码的详细介绍请参见[用户认证错误码](errorcode-useriam.md)。
1001
1002| 错误码ID | 错误信息 |
1003| -------- | ------- |
1004| 401 | Incorrect parameters. |
1005| 12500002 | General operation error. |
1006| 12500005 | The authentication type is not supported. |
1007| 12500006 | The authentication trust level is not supported. |
1008
1009**示例:**
1010
1011```ts
1012import { userAuth } from '@kit.UserAuthenticationKit';
1013
1014let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
1015let authType = userAuth.UserAuthType.FACE;
1016let authTrustLevel = userAuth.AuthTrustLevel.ATL1;
1017
1018try {
1019  let auth = userAuth.getAuthInstance(challenge, authType, authTrustLevel);
1020  console.info('let auth instance success');
1021} catch (error) {
1022  console.error(`get auth instance success failed, error = ${error}`);
1023}
1024```
1025
1026## userAuth.getAvailableStatus<sup>9+</sup>
1027
1028getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel): void
1029
1030查询指定类型和等级的认证能力是否支持。
1031
1032**需要权限**:ohos.permission.ACCESS_BIOMETRIC
1033
1034**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1035
1036**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1037
1038**参数:**
1039
1040| 参数名         | 类型                               | 必填 | 说明                       |
1041| -------------- | ---------------------------------- | ---- | -------------------------- |
1042| authType       | [UserAuthType](#userauthtype8)     | 是   | 认证类型。从 API version 11 开始支持PIN查询。|
1043| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | 是   | 认证信任等级。       |
1044
1045> **错误码返回顺序说明:**
1046>
1047> - 无对应执行器注册时,判断系统不支持该认证能力,需返回12500005。
1048> - 有对应执行器注册时,功能未禁用,但认证安全等级低于业务指定时,需返回12500006。
1049> - 有对应执行器注册时,功能未禁用,但用户没有注册凭据时,需返回12500010。
1050> - 有对应执行器注册时,功能未禁用,但密码过期时,需返回12500013。
1051
1052**错误码:**
1053
1054以下错误码的详细介绍请参见[用户认证错误码](errorcode-useriam.md)。
1055
1056| 错误码ID | 错误信息 |
1057| -------- | ------- |
1058| 201 | Permission verification failed. |
1059| 401 | Incorrect parameters. Possible causes: 1.Mandatory parameters are left unspecified. |
1060| 12500002 | General operation error. |
1061| 12500005 | The authentication type is not supported. |
1062| 12500006 | The authentication trust level is not supported. |
1063| 12500010 | The type of credential has not been enrolled. |
1064| 12500013 | Operation failed because of PIN expired. |
1065
1066**示例:**
1067
1068```ts
1069import { userAuth } from '@kit.UserAuthenticationKit';
1070
1071try {
1072  userAuth.getAvailableStatus(userAuth.UserAuthType.FACE, userAuth.AuthTrustLevel.ATL1);
1073  console.info('current auth trust level is supported');
1074} catch (error) {
1075  console.error(`current auth trust level is not supported, error = ${error}`);
1076}
1077```
1078
1079## UserAuthResultCode<sup>9+</sup>
1080
1081表示返回码的枚举。
1082
1083**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1084
1085**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1086
1087| 名称                    |   值   | 说明                 |
1088| ----------------------- | ------ | -------------------- |
1089| SUCCESS                 | 12500000      | 执行成功。           |
1090| FAIL                    | 12500001      | 认证失败。           |
1091| GENERAL_ERROR           | 12500002      | 操作通用错误。       |
1092| CANCELED                | 12500003      | 操作取消。           |
1093| TIMEOUT                 | 12500004      | 操作超时。           |
1094| TYPE_NOT_SUPPORT        | 12500005      | 不支持的认证类型。   |
1095| TRUST_LEVEL_NOT_SUPPORT | 12500006      | 不支持的认证等级。   |
1096| BUSY                    | 12500007      | 忙碌状态。           |
1097| LOCKED                  | 12500009      | 认证器已锁定。       |
1098| NOT_ENROLLED            | 12500010      | 用户未录入认证信息。 |
1099| CANCELED_FROM_WIDGET<sup>10+</sup> | 12500011 | 当前的认证操作被用户从组件取消。返回这个错误码,表示使用应用自定义认证。 |
1100| PIN_EXPIRED<sup>12+</sup> | 12500013 | 当前的认证操作执行失败。返回这个错误码,表示系统锁屏密码过期。 |
1101
1102## UserAuth<sup>(deprecated)</sup>
1103
1104认证器对象。
1105
1106### constructor<sup>(deprecated)</sup>
1107
1108constructor()
1109
1110创建认证器对象。
1111
1112> **说明:**
1113> 从 API version 8 开始支持,从 API version 9 开始废弃,请使用[getAuthInstance](#userauthgetauthinstancedeprecated)替代。
1114
1115**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1116
1117**示例:**
1118
1119```ts
1120import { userAuth } from '@kit.UserAuthenticationKit';
1121
1122let auth = new userAuth.UserAuth();
1123```
1124
1125### getVersion<sup>(deprecated)</sup>
1126
1127getVersion() : number
1128
1129获取认证器的版本信息。
1130
1131> **说明:**
1132> 从 API version 8 开始支持,从 API version 9 开始废弃。
1133
1134**需要权限**:ohos.permission.ACCESS_BIOMETRIC
1135
1136**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1137
1138**返回值:**
1139
1140| 类型   | 说明                   |
1141| ------ | ---------------------- |
1142| number | 认证器版本信息。 |
1143
1144**示例:**
1145
1146```ts
1147import { userAuth } from '@kit.UserAuthenticationKit';
1148
1149let auth = new userAuth.UserAuth();
1150let version = auth.getVersion();
1151console.info(`auth version = ${version}`);
1152```
1153
1154### getAvailableStatus<sup>(deprecated)</sup>
1155
1156getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel) : number
1157
1158查询指定类型和等级的认证能力是否支持。
1159
1160> **说明:**
1161> 从 API version 8 开始支持,从 API version 9 开始废弃,请使用[getAvailableStatus](#userauthgetavailablestatus9)替代。
1162
1163**需要权限**:ohos.permission.ACCESS_BIOMETRIC
1164
1165**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1166
1167**参数:**
1168
1169| 参数名         | 类型                               | 必填 | 说明                       |
1170| -------------- | ---------------------------------- | ---- | -------------------------- |
1171| authType       | [UserAuthType](#userauthtype8)     | 是   | 认证类型,当前支持FACE和FINGERPRINT。 |
1172| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | 是   | 认证信任等级。       |
1173
1174**返回值:**
1175
1176| 类型   | 说明                                                         |
1177| ------ | ------------------------------------------------------------ |
1178| number | 查询结果,结果为SUCCESS时表示支持,其他返回值参见[ResultCode](#resultcodedeprecated)。 |
1179
1180**示例:**
1181
1182```ts
1183import { userAuth } from '@kit.UserAuthenticationKit';
1184
1185let auth = new userAuth.UserAuth();
1186let checkCode = auth.getAvailableStatus(userAuth.UserAuthType.FACE, userAuth.AuthTrustLevel.ATL1);
1187if (checkCode == userAuth.ResultCode.SUCCESS) {
1188  console.info('check auth support success');
1189} else {
1190  console.error(`check auth support fail, code = ${checkCode}`);
1191}
1192```
1193
1194### auth<sup>(deprecated)</sup>
1195
1196auth(challenge: Uint8Array, authType: UserAuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array
1197
1198执行用户认证,使用回调函数返回结果。
1199
1200> **说明:**
1201> 从 API version 8 开始支持,从 API version 9 开始废弃,建议使用[start](#startdeprecated)代替。
1202
1203**需要权限**:ohos.permission.ACCESS_BIOMETRIC
1204
1205**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1206
1207**参数:**
1208
1209| 参数名         | 类型                                     | 必填 | 说明                     |
1210| -------------- | ---------------------------------------- | ---- | ------------------------ |
1211| challenge      | Uint8Array                               | 是   | 挑战值,可以传Uint8Array([])。 |
1212| authType       | [UserAuthType](#userauthtype8)           | 是   | 认证类型,当前支持FACE和FINGERPRINT。 |
1213| authTrustLevel | [AuthTrustLevel](#authtrustlevel8)       | 是   | 认证信任等级。             |
1214| callback       | [IUserAuthCallback](#iuserauthcallbackdeprecated) | 是   | 回调函数。        |
1215
1216**返回值:**
1217
1218| 类型       | 说明                                                         |
1219| ---------- | ------------------------------------------------------------ |
1220| Uint8Array | ContextId,作为取消认证[cancelAuth](#cancelauthdeprecated)接口的入参。 |
1221
1222**示例:**
1223
1224```ts
1225import { userAuth } from '@kit.UserAuthenticationKit';
1226
1227let auth = new userAuth.UserAuth();
1228let challenge = new Uint8Array([]);
1229auth.auth(challenge, userAuth.UserAuthType.FACE, userAuth.AuthTrustLevel.ATL1, {
1230  onResult: (result, extraInfo) => {
1231    try {
1232      console.info(`auth onResult result = ${result}`);
1233      console.info(`auth onResult extraInfo = ${JSON.stringify(extraInfo)}`);
1234      if (result == userAuth.ResultCode.SUCCESS) {
1235        // 此处添加认证成功逻辑
1236      } else {
1237        // 此处添加认证失败逻辑
1238      }
1239    } catch (error) {
1240      console.error(`auth onResult error = ${error}`);
1241    }
1242  }
1243});
1244```
1245
1246### cancelAuth<sup>(deprecated)</sup>
1247
1248cancelAuth(contextID : Uint8Array) : number
1249
1250表示通过contextID取消本次认证操作。
1251
1252> **说明:**
1253> 从 API version 8 开始支持,从 API version 9 开始废弃,建议使用[cancel](#canceldeprecated)代替。
1254
1255**需要权限**:ohos.permission.ACCESS_BIOMETRIC
1256
1257**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1258
1259**参数:**
1260
1261| 参数名    | 类型       | 必填 | 说明                                       |
1262| --------- | ---------- | ---- | ------------------------------------------ |
1263| contextID | Uint8Array | 是   | 上下文的标识,通过[auth](#authdeprecated)接口获取。 |
1264
1265**返回值:**
1266
1267| 类型   | 说明                     |
1268| ------ | ------------------------ |
1269| number | 取消认证的结果,结果为SUCCESS时表示取消成功,其他返回值参见[ResultCode](#resultcodedeprecated)。 |
1270
1271**示例:**
1272
1273```ts
1274import { userAuth } from '@kit.UserAuthenticationKit';
1275
1276// contextId可通过auth接口获取,此处直接定义
1277let contextId = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]);
1278let auth = new userAuth.UserAuth();
1279let cancelCode = auth.cancelAuth(contextId);
1280if (cancelCode == userAuth.ResultCode.SUCCESS) {
1281  console.info('cancel auth success');
1282} else {
1283  console.error('cancel auth fail');
1284}
1285```
1286
1287## IUserAuthCallback<sup>(deprecated)</sup>
1288
1289返回认证结果的回调对象。
1290
1291> **说明:**
1292> 从 API version 8 开始支持,从 API version 9 开始废弃,建议使用[AuthEvent](#autheventdeprecated)代替。
1293
1294### onResult<sup>(deprecated)</sup>
1295
1296onResult: (result : number, extraInfo : AuthResult) => void
1297
1298回调函数,返回认证结果。
1299
1300> **说明:**
1301> 从 API version 8 开始支持,从 API version 9 开始废弃,建议使用[callback](#callbackdeprecated)代替。
1302
1303**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1304
1305**参数:**
1306
1307| 参数名    | 类型                       | 必填 | 说明        |
1308| --------- | -------------------------- | ---- | ------------------------------------------------ |
1309| result    | number           | 是   | 认证结果,参见[ResultCode](#resultcodedeprecated)。 |
1310| extraInfo | [AuthResult](#authresultdeprecated) | 是   | 扩展信息,不同情况下的具体信息,<br/>如果身份验证通过,则在extraInfo中返回用户认证令牌,<br/>如果身份验证失败,则在extraInfo中返回剩余的用户认证次数,<br/>如果身份验证执行器被锁定,则在extraInfo中返回冻结时间。 |
1311
1312**示例:**
1313
1314```ts
1315import { userAuth } from '@kit.UserAuthenticationKit';
1316
1317let auth = new userAuth.UserAuth();
1318let challenge = new Uint8Array([]);
1319auth.auth(challenge, userAuth.UserAuthType.FACE, userAuth.AuthTrustLevel.ATL1, {
1320  onResult: (result, extraInfo) => {
1321    try {
1322      console.info(`auth onResult result = ${result}`);
1323      console.info(`auth onResult extraInfo = ${JSON.stringify(extraInfo)}`);
1324      if (result == userAuth.ResultCode.SUCCESS) {
1325        // 此处添加认证成功逻辑
1326      }  else {
1327        // 此处添加认证失败逻辑
1328      }
1329    } catch (error) {
1330      console.error(`auth onResult error = ${error}`);
1331    }
1332  }
1333});
1334```
1335
1336### onAcquireInfo<sup>(deprecated)</sup>
1337
1338onAcquireInfo ?: (module : number, acquire : number, extraInfo : any) => void
1339
1340回调函数,返回认证过程中的提示信息,非必须实现。
1341
1342> **说明:**
1343> 从 API version 8 开始支持,从 API version 9 开始废弃,建议使用[callback](#callbackdeprecated)代替。
1344
1345**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1346
1347**参数:**
1348
1349| 参数名    | 类型   | 必填 | 说明                           |
1350| --------- | ------ | ---- | ------------------------------ |
1351| module    | number | 是   | 发送提示信息的模块标识。             |
1352| acquire   | number | 是   | 认证执过程中的提示信息。 |
1353| extraInfo | any    | 是   | 预留字段。                     |
1354
1355**示例:**
1356
1357```ts
1358import { userAuth } from '@kit.UserAuthenticationKit';
1359
1360let auth = new userAuth.UserAuth();
1361let challenge = new Uint8Array([]);
1362auth.auth(challenge, userAuth.UserAuthType.FACE, userAuth.AuthTrustLevel.ATL1, {
1363  onResult: (result, extraInfo) => {
1364    try {
1365      console.info(`auth onResult result = ${result}`);
1366      console.info(`auth onResult extraInfo = ${JSON.stringify(extraInfo)}`);
1367      if (result == userAuth.ResultCode.SUCCESS) {
1368        // 此处添加认证成功逻辑
1369      }  else {
1370        // 此处添加认证失败逻辑
1371      }
1372    } catch (error) {
1373      console.error(`auth onResult error = ${error}`);
1374    }
1375  },
1376  onAcquireInfo: (module, acquire, extraInfo : userAuth.AuthResult) => {
1377    try {
1378      console.info(`auth onAcquireInfo module = ${module}`);
1379      console.info(`auth onAcquireInfo acquire = ${acquire}`);
1380      console.info(`auth onAcquireInfo extraInfo = ${JSON.stringify(extraInfo)}`);
1381    } catch (error) {
1382      console.error(`auth onAcquireInfo error = ${error}`);
1383    }
1384  }
1385});
1386```
1387
1388## AuthResult<sup>(deprecated)</sup>
1389
1390表示认证结果的对象。
1391
1392> **说明:**
1393> 从 API version 8 开始支持,从 API version 9 开始废弃,建议使用[AuthResultInfo](#authresultinfodeprecated)代替。
1394
1395**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1396
1397| 名称         | 类型   | 必填 | 说明                 |
1398| ------------ | ---------- | ---- | -------------------|
1399| token        | Uint8Array | 否   | 认证通过的令牌信息。 |
1400| remainTimes  | number     | 否   | 剩余的认证操作次数。 |
1401| freezingTime | number     | 否   | 认证操作的冻结时间。 |
1402
1403## ResultCode<sup>(deprecated)</sup>
1404
1405表示返回码的枚举。
1406
1407> **说明:**
1408> 从 API version 9 开始废弃,建议使用[UserAuthResultCode](#userauthresultcode9)代替。
1409
1410**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1411
1412| 名称                    | 值 | 说明                 |
1413| ----------------------- | ------ | -------------------- |
1414| SUCCESS                 | 0      | 执行成功。           |
1415| FAIL                    | 1      | 认证失败。           |
1416| GENERAL_ERROR           | 2      | 操作通用错误。       |
1417| CANCELED                | 3      | 操作取消。           |
1418| TIMEOUT                 | 4      | 操作超时。           |
1419| TYPE_NOT_SUPPORT        | 5      | 不支持的认证类型。   |
1420| TRUST_LEVEL_NOT_SUPPORT | 6      | 不支持的认证等级。   |
1421| BUSY                    | 7      | 忙碌状态。           |
1422| INVALID_PARAMETERS      | 8      | 无效参数。           |
1423| LOCKED                  | 9      | 认证器已锁定。       |
1424| NOT_ENROLLED            | 10     | 用户未录入认证信息。 |
1425
1426## FaceTips<sup>(deprecated)</sup>
1427
1428表示人脸认证过程中提示码的枚举。
1429
1430> **说明:**
1431> 从 API version 8 开始支持,从 API version 11 开始废弃。
1432
1433**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1434
1435| 名称                          |   值   |    说明                             |
1436| ----------------------------- | ------ | ------------------------------------ |
1437| FACE_AUTH_TIP_TOO_BRIGHT      | 1      | 光线太强,获取的图像太亮。           |
1438| FACE_AUTH_TIP_TOO_DARK        | 2      | 光线太暗,获取的图像太暗。           |
1439| FACE_AUTH_TIP_TOO_CLOSE       | 3      | 人脸距离设备过近。                   |
1440| FACE_AUTH_TIP_TOO_FAR         | 4      | 人脸距离设备过远。                   |
1441| FACE_AUTH_TIP_TOO_HIGH        | 5      | 设备太高,仅获取到人脸上部。         |
1442| FACE_AUTH_TIP_TOO_LOW         | 6      | 设备太低,仅获取到人脸下部。         |
1443| FACE_AUTH_TIP_TOO_RIGHT       | 7      | 设备太靠右,仅获取到人脸右部。       |
1444| FACE_AUTH_TIP_TOO_LEFT        | 8      | 设备太靠左,仅获取到人脸左部。       |
1445| FACE_AUTH_TIP_TOO_MUCH_MOTION | 9      | 在图像采集过程中,用户人脸移动太快。 |
1446| FACE_AUTH_TIP_POOR_GAZE       | 10     | 没有正视摄像头。                     |
1447| FACE_AUTH_TIP_NOT_DETECTED    | 11     | 没有检测到人脸信息。                 |
1448
1449
1450## FingerprintTips<sup>(deprecated)</sup>
1451
1452表示指纹认证过程中提示码的枚举。
1453
1454> **说明:**
1455> 从 API version 8 开始支持,从 API version 11 开始废弃。
1456
1457**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1458
1459| 名称                              |   值   | 说明                                               |
1460| --------------------------------- | ------ | -------------------------------------------------- |
1461| FINGERPRINT_AUTH_TIP_GOOD         | 0      | 获取的指纹图像良好。                               |
1462| FINGERPRINT_AUTH_TIP_DIRTY        | 1      | 由于传感器上可疑或检测到的污垢,指纹图像噪音过大。 |
1463| FINGERPRINT_AUTH_TIP_INSUFFICIENT | 2      | 由于检测到的情况,指纹图像噪声太大,无法处理。     |
1464| FINGERPRINT_AUTH_TIP_PARTIAL      | 3      | 仅检测到部分指纹图像。                             |
1465| FINGERPRINT_AUTH_TIP_TOO_FAST     | 4      | 快速移动,指纹图像不完整。                         |
1466| FINGERPRINT_AUTH_TIP_TOO_SLOW     | 5      | 缺少运动,指纹图像无法读取。                       |
1467
1468
1469## UserAuthType<sup>8+</sup>
1470
1471表示身份认证的凭据类型枚举。
1472
1473**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1474
1475**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1476
1477| 名称        | 值   | 说明       |
1478| ----------- | ---- | ---------- |
1479| PIN<sup>10+</sup>         | 1    | 口令认证。 |
1480| FACE        | 2    | 人脸认证。 |
1481| FINGERPRINT | 4    | 指纹认证。 |
1482
1483## AuthTrustLevel<sup>8+</sup>
1484
1485表示认证结果的信任等级枚举。
1486
1487典型场景及举例可参考[认证可信等级划分原则](../../security/UserAuthenticationKit/user-authentication-overview.md)。
1488
1489**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1490
1491**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1492
1493| 名称 | 值    | 说明                                                         |
1494| ---- | ----- | ------------------------------------------------------------ |
1495| ATL1 | 10000 | 认证结果的信任等级级别1,代表该认证方案能够识别用户个体,有一定的活体检测能力。常用的业务场景有业务风控、一般个人数据查询等。 |
1496| ATL2 | 20000 | 认证结果的信任等级级别2,代表该认证方案能够精确识别用户个体,有一定的活体检测能力。常用的业务场景有维持设备解锁状态,应用登录等。 |
1497| ATL3 | 30000 | 认证结果的信任等级级别3,代表该认证方案能够精确识别用户个体,有较强的活体检测能力。常用的业务场景有设备解锁等。 |
1498| ATL4 | 40000 | 认证结果的信任等级级别4,代表该认证方案能够高精度的识别用户个体,有很强的活体检测能力。常用的业务场景有小额支付等。 |
1499
1500## SecureLevel<sup>(deprecated)</sup>
1501
1502type SecureLevel = string
1503
1504表示认证的安全级别。
1505
1506**原子化服务API:** 从 API version 6 开始支持,从 API version 8 开始废弃。
1507
1508**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1509
1510| 类型 | 说明                                                         |
1511| ---- | ------------------------------------------------------------ |
1512| string | 表示类型为字符,认证的安全级别包括:`'S1'` \| `'S2' `\|`'S3'`\|`'S4'`。 <br/>\- `'S1'`:认证结果的信任等级级别1,代表该认证方案能够识别用户个体,有一定的活体检测能力。常用的业务场景有业务风控、一般个人数据查询等。 <br/>\- `'S2'`:认证结果的信任等级级别2,代表该认证方案能够精确识别用户个体,有一定的活体检测能力。常用的业务场景有维持设备解锁状态,应用登录等。 <br/>\- `'S3'`:认证结果的信任等级级别3,代表该认证方案能够精确识别用户个体,有较强的活体检测能力。常用的业务场景有设备解锁等。 <br/>\- `'S4'`:认证结果的信任等级级别4,代表该认证方案能够高精度的识别用户个体,有很强的活体检测能力。常用的业务场景有小额支付等。 |
1513
1514## AuthType<sup>(deprecated)</sup>
1515
1516type AuthType = string
1517
1518表示认证类型。
1519
1520**原子化服务API:** 从 API version 6 开始支持,从 API version 8 开始废弃。
1521
1522**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1523
1524| 类型 | 说明                                                         |
1525| ---- | ------------------------------------------------------------ |
1526| string  | 表示认证类型为字符,认证类型包括:`'ALL'`\|`'FACE_ONLY'`。<br/>\- `'ALL'`:预留参数,当前版本暂不支持ALL类型的认证。<br/>\- `'FACE_ONLY'`:人脸认证。 |
1527
1528## userAuth.getAuthenticator<sup>(deprecated)</sup>
1529
1530getAuthenticator(): Authenticator
1531
1532获取Authenticator对象,用于执行用户身份认证。
1533
1534> **说明:**
1535> 从 API version 8 开始废弃,建议使用[constructor](#constructordeprecated)替代。
1536
1537**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1538
1539**返回值:**
1540
1541| 类型                                      | 说明         |
1542| ----------------------------------------- | ------------ |
1543| [Authenticator](#authenticatordeprecated) | 认证器对象。 |
1544
1545**示例:**
1546  ```ts
1547  import { userAuth } from '@kit.UserAuthenticationKit';
1548
1549  let authenticator = userAuth.getAuthenticator();
1550  ```
1551
1552## Authenticator<sup>(deprecated)</sup>
1553
1554认证器对象。
1555
1556> **说明:**
1557> 从 API version 8 开始废弃,建议使用[UserAuth](#userauthdeprecated)替代。
1558
1559### execute<sup>(deprecated)</sup>
1560
1561execute(type: AuthType, level: SecureLevel, callback: AsyncCallback&lt;number&gt;): void
1562
1563执行用户认证,使用callback方式作为异步方法。
1564
1565> **说明:**
1566> 从 API version 8 开始废弃,建议使用[auth](#authdeprecated)替代。
1567
1568**需要权限**:ohos.permission.ACCESS_BIOMETRIC
1569
1570**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1571
1572**参数:**
1573
1574| 参数名   | 类型                        | 必填 | 说明                                                                                                                    |
1575| -------- | --------------------------- | ---- |-----------------------------------------------------------------------------------------------------------------------|
1576| type     | AuthType                      | 是   | 认证类型,当前只支持"FACE_ONLY"。<br/>ALL为预留参数。当前版本暂不支持ALL类型的认证。                                                                 |
1577| level    | SecureLevel  | 是   | 安全级别,对应认证的安全级别,有效值为"S1"(最低)、"S2"、"S3"、"S4"(最高)。<br/>具备3D人脸识别能力的设备支持"S3"及以下安全级别的认证。<br/>具备2D人脸识别能力的设备支持"S2"及以下安全级别的认证。 |
1578| callback | AsyncCallback&lt;number&gt; | 是 | 回调函数。number表示认证结果,参见[AuthenticationResult](#authenticationresultdeprecated)。 |
1579
1580**示例:**
1581
1582```ts
1583import { userAuth } from '@kit.UserAuthenticationKit';
1584
1585let authenticator = userAuth.getAuthenticator();
1586authenticator.execute('FACE_ONLY', 'S2', (error, code)=>{
1587  if (code === userAuth.ResultCode.SUCCESS) {
1588    console.info('auth success');
1589    return;
1590  }
1591  console.error(`auth fail, code = ${code}`);
1592});
1593```
1594
1595
1596### execute<sup>(deprecated)</sup>
1597
1598execute(type : AuthType, level : SecureLevel): Promise&lt;number&gt;
1599
1600执行用户认证,使用promise方式作为异步方法。
1601
1602> **说明:**
1603> 从 API version 8 开始废弃,建议使用[auth](#authdeprecated)替代。
1604
1605**需要权限**:ohos.permission.ACCESS_BIOMETRIC
1606
1607**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1608
1609**参数:**
1610
1611| 参数名 | 类型   | 必填 | 说明                                                                                                                    |
1612| ------ | ------ | ---- |-----------------------------------------------------------------------------------------------------------------------|
1613| type   | AuthType | 是   | 认证类型,当前只支持"FACE_ONLY"。<br/>ALL为预留参数。当前版本暂不支持ALL类型的认证。                                                                 |
1614| level  | SecureLevel | 是   | 安全级别,对应认证的安全级别,有效值为"S1"(最低)、"S2"、"S3"、"S4"(最高)。<br/>具备3D人脸识别能力的设备支持"S3"及以下安全级别的认证。<br/>具备2D人脸识别能力的设备支持"S2"及以下安全级别的认证。 |
1615
1616**返回值:**
1617
1618| 类型                  | 说明                                                         |
1619| --------------------- | ------------------------------------------------------------ |
1620| Promise&lt;number&gt; | 返回携带一个number的Promise。number&nbsp;为认证结果,参见[AuthenticationResult](#authenticationresultdeprecated)。 |
1621
1622**示例:**
1623
1624```ts
1625import { userAuth } from '@kit.UserAuthenticationKit';
1626
1627try {
1628  let authenticator = userAuth.getAuthenticator();
1629  authenticator.execute('FACE_ONLY', 'S2').then((code)=>{
1630    console.info('auth success');
1631  })
1632} catch (error) {
1633  console.error(`auth fail, code = ${error}`);
1634}
1635```
1636
1637## AuthenticationResult<sup>(deprecated)</sup>
1638
1639表示认证结果的枚举。
1640
1641> **说明:**
1642> 从 API version 8 开始废弃,建议使用[ResultCode](#resultcodedeprecated)替代。
1643
1644**系统能力**:SystemCapability.UserIAM.UserAuth.Core
1645
1646| 名称               |   值   | 说明                       |
1647| ------------------ | ------ | -------------------------- |
1648| NO_SUPPORT         | -1     | 设备不支持当前的认证方式。 |
1649| SUCCESS            | 0      | 认证成功。                 |
1650| COMPARE_FAILURE    | 1      | 比对失败。                 |
1651| CANCELED           | 2      | 用户取消认证。             |
1652| TIMEOUT            | 3      | 认证超时。                 |
1653| CAMERA_FAIL        | 4      | 开启相机失败。             |
1654| BUSY               | 5      | 认证服务忙,请稍后重试。   |
1655| INVALID_PARAMETERS | 6      | 认证参数无效。             |
1656| LOCKED             | 7      | 认证失败次数过多,已锁定。 |
1657| NOT_ENROLLED       | 8      | 未录入认证凭据。           |
1658| GENERAL_ERROR      | 100    | 其他错误。                 |
1659
1660