• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.userIAM.userAuth (用户认证)(系统接口)
2
3<!--Kit: User Authentication Kit-->
4<!--Subsystem: UserIAM-->
5<!--Owner: @WALL_EYE-->
6<!--Designer: @lichangting518-->
7<!--Tester: @jane_lz-->
8<!--Adviser: @zengyawen-->
9
10提供用户认证能力,可应用于设备解锁、支付、应用登录等身份认证场景。
11
12> **说明:**
13>
14> - 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
15> - 当前页面仅包含本模块的系统接口,其他公开接口参见[@ohos.userIAM.userAuth (用户认证)](js-apis-useriam-userauth.md)。
16
17## 导入模块
18
19```ts
20import { userAuth } from '@kit.UserAuthenticationKit';
21```
22
23## AuthParam<sup>10+</sup>
24
25用户认证相关参数。
26
27**系统能力**:SystemCapability.UserIAM.UserAuth.Core
28
29| 名称           | 类型                               | 必填 | 说明                                                         |
30| -------------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
31| userId<sup>18+</sup> | number | 否   |要认证的目标用户ID,值为大于等于0的正整数。默认值为当前用户的ID。<br>**系统接口**: 此接口为系统接口。|
32
33## WindowModeType<sup>10+</sup>
34
35用户认证界面的显示类型。
36
37**系统能力**:SystemCapability.UserIAM.UserAuth.Core
38
39**系统接口**: 此接口为系统接口。
40
41| 名称       | 值   | 说明       |
42| ---------- | ---- | ---------- |
43| DIALOG_BOX | 1    | 弹框类型。 |
44| FULLSCREEN | 2    | 全屏类型。 |
45
46## WidgetParam<sup>10+</sup>
47
48用户认证界面配置相关参数。
49
50**系统能力**:SystemCapability.UserIAM.UserAuth.Core
51
52| 名称                 | 类型                                | 必填 | 说明                                                         |
53| -------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ |
54| windowMode           | [WindowModeType](#windowmodetype10) | 否   | 代表用户认证界面的显示类型,默认值为WindowModeType.DIALOG_BOX。<br>**系统接口**: 此接口为系统接口。 |
55
56## NoticeType<sup>10+</sup>
57
58用户身份认证的通知类型。
59
60**系统能力**:SystemCapability.UserIAM.UserAuth.Core
61
62**系统接口**: 此接口为系统接口。
63
64| 名称          | 值   | 说明                 |
65| ------------- | ---- | -------------------- |
66| WIDGET_NOTICE | 1    | 表示来自组件的通知。 |
67
68## userAuth.sendNotice<sup>10+</sup>
69
70sendNotice(noticeType: NoticeType, eventData: string): void
71
72在使用统一身份认证控件进行用户身份认证时,用于接收来自统一身份认证控件的通知。
73
74**需要权限**:ohos.permission.SUPPORT_USER_AUTH
75
76**系统能力**:SystemCapability.UserIAM.UserAuth.Core
77
78**系统接口**: 此接口为系统接口。
79
80**参数:**
81
82| 参数名     | 类型                        | 必填 | 说明       |
83| ---------- | --------------------------- | ---- | ---------- |
84| noticeType | [NoticeType](#noticetype10) | 是   | 通知类型。 |
85| eventData  | string                | 是   | 事件数据。数据长度限制为0-65536。    |
86
87**错误码:**
88
89以下错误码的详细介绍请参见[用户认证错误码](errorcode-useriam.md)。
90
91| 错误码ID | 错误信息                                |
92| -------- | --------------------------------------- |
93| 201      | Permission denied.       |
94| 202      | Permission denied. Called by non-system application. |
95| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.    |
96| 12500002 | General operation error.                |
97
98**示例:**
99
100```ts
101import { userAuth } from '@kit.UserAuthenticationKit';
102import { BusinessError } from '@kit.BasicServicesKit';
103
104interface  EventData {
105  widgetContextId: number;
106  event: string;
107  version: string;
108  payload: PayLoad;
109}
110interface PayLoad {
111  type: string[];
112}
113try {
114  const eventData : EventData = {
115    widgetContextId: 123456,
116    event: 'EVENT_AUTH_TYPE_READY',
117    version: '1',
118    payload: {
119      type: ['pin']
120    } as PayLoad,
121  };
122  const jsonEventData = JSON.stringify(eventData);
123  let noticeType = userAuth.NoticeType.WIDGET_NOTICE;
124  userAuth.sendNotice(noticeType, jsonEventData);
125  console.info('sendNotice success');
126} catch (error) {
127  const err: BusinessError = error as BusinessError;
128  console.error(`sendNotice catch error: Code is ${err?.code}, message is ${err?.message}`);
129}
130```
131
132## UserAuthWidgetMgr<sup>10+</sup>
133
134组件管理接口,可将用身份认证控件注册到UserAuthWidgetMgr中,由UserAuthWidgetMgr进行管理、调度。
135
136### on<sup>10+</sup>
137
138on(type: 'command', callback: IAuthWidgetCallback): void
139
140身份认证控件订阅来自用户认证框架的命令。
141
142**系统能力**:SystemCapability.UserIAM.UserAuth.Core
143
144**系统接口**: 此接口为系统接口。
145
146**参数:**
147
148| 参数名   | 类型                                          | 必填 | 说明                                                         |
149| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
150| type     | 'command'                                     | 是   | 订阅事件类型,表明该事件用于用户认证框架向身份认证控件发送命令。 |
151| callback | [IAuthWidgetCallback](#iauthwidgetcallback10) | 是   | 组件管理接口的回调函数,用于用户认证框架向身份认证控件发送命令。 |
152
153**错误码:**
154
155以下错误码的详细介绍请参见[用户认证错误码](errorcode-useriam.md)。
156
157| 错误码ID | 错误信息                 |
158| -------- | ------------------------ |
159| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
160| 12500002 | General operation error. |
161
162**示例:**
163
164```ts
165import { userAuth } from '@kit.UserAuthenticationKit';
166import { BusinessError } from '@kit.BasicServicesKit';
167
168const userAuthWidgetMgrVersion = 1;
169try {
170  let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion);
171  console.info('get userAuthWidgetMgr instance success');
172  userAuthWidgetMgr.on('command', {
173    sendCommand(cmdData) {
174      console.info(`The cmdData is ${cmdData}`);
175    }
176  })
177  console.info('subscribe authentication event success');
178} catch (error) {
179  const err: BusinessError = error as BusinessError;
180  console.error(`userAuth widgetMgr catch error: Code is ${err?.code}, message is ${err?.message}`);
181}
182```
183
184### off<sup>10+</sup>
185
186off(type: 'command', callback?: IAuthWidgetCallback): void
187
188身份认证控件取消订阅来自用户认证框架的命令。
189
190**系统能力**:SystemCapability.UserIAM.UserAuth.Core
191
192**系统接口**: 此接口为系统接口。
193
194**参数:**
195
196| 参数名   | 类型                                          | 必填 | 说明                                                         |
197| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
198| type     | 'command'                                     | 是   | 订阅事件类型,表明该事件用于用户认证框架向身份认证控件发送命令。 |
199| callback | [IAuthWidgetCallback](#iauthwidgetcallback10) | 否   | 组件管理接口的回调函数,用于用户认证框架向身份认证控件发送命令。 |
200
201**错误码:**
202
203以下错误码的详细介绍请参见[用户认证错误码](errorcode-useriam.md)。
204
205| 错误码ID | 错误信息                 |
206| -------- | ------------------------ |
207| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
208| 12500002 | General operation error. |
209
210**示例:**
211
212```ts
213import { userAuth } from '@kit.UserAuthenticationKit';
214import { BusinessError } from '@kit.BasicServicesKit';
215
216const userAuthWidgetMgrVersion = 1;
217try {
218  let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion);
219  console.info('get userAuthWidgetMgr instance success');
220  userAuthWidgetMgr.off('command', {
221    sendCommand(cmdData) {
222      console.info(`The cmdData is ${cmdData}`);
223    }
224  })
225  console.info('cancel subscribe authentication event success');
226} catch (error) {
227  const err: BusinessError = error as BusinessError;
228  console.error(`userAuth widgetMgr catch error: Code is ${err?.code}, message is ${err?.message}`);
229}
230```
231
232## userAuth.getUserAuthWidgetMgr<sup>10+</sup>
233
234getUserAuthWidgetMgr(version: number): UserAuthWidgetMgr
235
236获取UserAuthWidgetMgr对象,用于执行用户身份认证。
237
238> **说明:**
239> 每个UserAuthInstance只能进行一次认证,若需要再次进行认证则需重新获取UserAuthInstance。
240
241**需要权限**:ohos.permission.SUPPORT_USER_AUTH
242
243**系统能力**:SystemCapability.UserIAM.UserAuth.Core
244
245**系统接口**: 此接口为系统接口。
246
247**参数:**
248
249| 参数名  | 类型   | 必填 | 说明                 |
250| ------- | ------ | ---- | -------------------- |
251| version | number | 是   | 表示认证组件的版本。 |
252
253**返回值:**
254
255| 类型                                      | 说明         |
256| ----------------------------------------- | ------------ |
257| [UserAuthWidgetMgr](#userauthwidgetmgr10) | 认证器对象。 |
258
259**错误码:**
260
261以下错误码的详细介绍请参见[用户认证错误码](errorcode-useriam.md)。
262
263| 错误码ID | 错误信息                                |
264| -------- | --------------------------------------- |
265| 201      | Permission denied.       |
266| 202      | Permission denied. Called by non-system application. |
267| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.                                     |
268| 12500002 | General operation error.                |
269
270**示例:**
271
272```ts
273import { userAuth } from '@kit.UserAuthenticationKit';
274import { BusinessError } from '@kit.BasicServicesKit';
275
276let userAuthWidgetMgrVersion = 1;
277try {
278  let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion);
279  console.info('get userAuthWidgetMgr instance success');
280} catch (error) {
281  const err: BusinessError = error as BusinessError;
282  console.error(`userAuth widgetMgr catch error: Code is ${err?.code}, message is ${err?.message}`);
283}
284```
285
286## IAuthWidgetCallback<sup>10+</sup>
287
288认证组件通过该回调获取用户认证框架发送的命令。
289
290### sendCommand<sup>10+</sup>
291
292sendCommand(cmdData: string): void
293
294回调函数,用于用户认证框架向组件发送命令。
295
296**系统能力**:SystemCapability.UserIAM.UserAuth.Core
297
298**系统接口**: 此接口为系统接口。
299
300**参数:**
301
302| 参数名  | 类型   | 必填 | 说明                               |
303| ------- | ------ | ---- | ---------------------------------- |
304| cmdData | string | 是   | 用户身份认证框架向控件发送的命令。 |
305
306**示例:**
307
308```ts
309import { userAuth } from '@kit.UserAuthenticationKit';
310import { BusinessError } from '@kit.BasicServicesKit';
311
312const userAuthWidgetMgrVersion = 1;
313try {
314  let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion);
315  console.info('get userAuthWidgetMgr instance success');
316  userAuthWidgetMgr.on('command', {
317    sendCommand(cmdData) {
318      console.info(`The cmdData is ${cmdData}`);
319    }
320  })
321  console.info('subscribe authentication event success');
322} catch (error) {
323  const err: BusinessError = error as BusinessError;
324  console.error(`userAuth widgetMgr catch error: Code is ${err?.code}, message is ${err?.message}`);
325}
326```
327
328## UserAuthType<sup>8+</sup>
329
330表示身份认证的凭据类型枚举。
331
332**系统能力**:SystemCapability.UserIAM.UserAuth.Core
333
334| 名称        | 值   | 说明       |
335| ----------- | ---- | ---------- |
336| PRIVATE_PIN<sup>14+</sup>  | 16   | 隐私口令。<br>**系统接口**: 此接口为系统接口。|
337
338**示例:**
339
340发起用户认证,采用认证可信等级≥ATL3的隐私密码认证,获取认证结果。
341
342```ts
343import { BusinessError } from '@kit.BasicServicesKit';
344import { cryptoFramework } from '@kit.CryptoArchitectureKit';
345import { userAuth } from '@kit.UserAuthenticationKit';
346
347try {
348  const rand = cryptoFramework.createRandom();
349  const len: number = 16;
350  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
351  const authParam: userAuth.AuthParam = {
352    challenge: randData,
353    authType: [userAuth.UserAuthType.PRIVATE_PIN],
354    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
355  };
356  const widgetParam: userAuth.WidgetParam = {
357    title: '请输入密码',
358  };
359
360  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
361  console.info('get userAuth instance success');
362  // 需要调用UserAuthInstance的start()接口,启动认证后,才能通过onResult获取到认证结果。
363  userAuthInstance.on('result', {
364    onResult (result) {
365      console.info(`userAuthInstance callback result = ${JSON.stringify(result)}`);
366    }
367  });
368  console.info('auth on success');
369  userAuthInstance.start();
370  console.info('auth start success');
371} catch (error) {
372  const err: BusinessError = error as BusinessError;
373  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
374}
375```
376
377## userAuth.queryReusableAuthResult<sup>20+</sup>
378
379queryReusableAuthResult(authParam: AuthParam): Uint8Array
380
381查询是否有可复用的身份认证结果。
382
383**需要权限**:ohos.permission.ACCESS_USER_AUTH_INTERNAL
384
385**系统能力**:SystemCapability.UserIAM.UserAuth.Core
386
387**系统接口**: 此接口为系统接口。
388
389**参数:**
390
391| 参数名  | 类型   | 必填 | 说明                 |
392| ------- | ------ | ---- | -------------------- |
393| authParam | [AuthParam](js-apis-useriam-userauth.md#authparam10) | 是 | 用户认证相关参数。|
394
395**返回值:**
396
397| 类型        | 说明                                 |
398| ---------- | ------------------------------------ |
399| Uint8Array | 可复用的AuthToken。最大长度为1024B。|
400
401**错误码:**
402
403以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[用户认证错误码](errorcode-useriam.md)。
404
405| 错误码ID | 错误信息                                |
406| -------- | --------------------------------------- |
407| 201      | Permission denied.       |
408| 202      | Permission denied. Called by non-system application. |
409| 12500002 | General operation error.                |
410| 12500008 | The parameter is out of range.          |
411| 12500017 | Failed to reuse authentication result.       |
412
413**示例:**
414
415```ts
416import { BusinessError } from '@kit.BasicServicesKit';
417import { cryptoFramework } from '@kit.CryptoArchitectureKit';
418import { userAuth } from '@kit.UserAuthenticationKit';
419
420try {
421  const rand = cryptoFramework.createRandom();
422  const len: number = 16;
423  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
424  const reuseUnlockResult: userAuth.ReuseUnlockResult = {
425    reuseMode: userAuth.ReuseMode.AUTH_TYPE_RELEVANT,
426    reuseDuration: userAuth.MAX_ALLOWABLE_REUSE_DURATION,
427  }
428  const authParam: userAuth.AuthParam = {
429    challenge: randData,
430    authType: [userAuth.UserAuthType.PIN],
431    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
432    reuseUnlockResult: reuseUnlockResult,
433  };
434  let authToken = userAuth.queryReusableAuthResult(authParam);
435  console.info('query reuse auth result success');
436} catch (error) {
437  const err: BusinessError = error as BusinessError;
438  console.error(`query reuse auth result catch error. Code is ${err?.code}, message is ${err?.message}`);
439}
440```
441
442## UserAuthResultCode<sup>18+</sup>
443
444表示返回码的枚举。
445
446**系统能力**:SystemCapability.UserIAM.UserAuth.Core
447
448**系统接口**: 此接口为系统接口。
449
450| 名称                    |   值   | 说明                 |
451| ----------------------- | ------ | -------------------- |
452| AUTH_TOKEN_CHECK_FAILED | 12500015      | verifyAuthToken系统接口错误码,表示验证的AuthToken无效。|
453| AUTH_TOKEN_EXPIRED      | 12500016      | verifyAuthToken系统接口错误码,AuthToken的签发时间至发起验证时的时间间隔超过传入的最大有效时长。|
454| REUSE_AUTH_RESULT_FAILED<sup>20+</sup>| 12500017      | queryReusableAuthResult系统接口错误码,表示复用身份认证结果失败。|