1# @ohos.userIAM.userAuth (用户认证)(系统接口)
2
3提供用户认证能力,可应用于设备解锁、支付、应用登录等身份认证场景。
4
5> **说明:**
6>
7> - 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8> - 当前页面仅包含本模块的系统接口,其他公开接口参见[@ohos.userIAM.userAuth (用户认证)](js-apis-useriam-userauth.md)。
9
10## 导入模块
11
12```ts
13import { userAuth } from '@kit.UserAuthenticationKit';
14```
15
16## WindowModeType<sup>10+</sup>
17
18用户认证界面的显示类型。
19
20**系统能力**:SystemCapability.UserIAM.UserAuth.Core
21
22**系统接口**: 此接口为系统接口。
23
24| 名称       | 值   | 说明       |
25| ---------- | ---- | ---------- |
26| DIALOG_BOX | 1    | 弹框类型。 |
27| FULLSCREEN | 2    | 全屏类型。 |
28
29## WidgetParam<sup>10+</sup>
30
31用户认证界面配置相关参数。
32
33**系统能力**:SystemCapability.UserIAM.UserAuth.Core
34
35| 名称                 | 类型                                | 必填 | 说明                                                         |
36| -------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ |
37| windowMode           | [WindowModeType](#windowmodetype10) | 否   | 代表用户认证界面的显示类型,默认值为WindowModeType.DIALOG_BOX。<br>**系统接口**: 此接口为系统接口。 |
38
39## NoticeType<sup>10+</sup>
40
41用户身份认证的通知类型。
42
43**系统能力**:SystemCapability.UserIAM.UserAuth.Core
44
45**系统接口**: 此接口为系统接口。
46
47| 名称          | 值   | 说明                 |
48| ------------- | ---- | -------------------- |
49| WIDGET_NOTICE | 1    | 表示来自组件的通知。 |
50
51## userAuth.sendNotice<sup>10+</sup>
52
53sendNotice(noticeType: NoticeType, eventData: string): void
54
55在使用统一身份认证控件进行用户身份认证时,用于接收来自统一身份认证控件的通知。
56
57**需要权限**:ohos.permission.SUPPORT_USER_AUTH
58
59**系统能力**:SystemCapability.UserIAM.UserAuth.Core
60
61**系统接口**: 此接口为系统接口。
62
63**参数:**
64
65| 参数名     | 类型                        | 必填 | 说明       |
66| ---------- | --------------------------- | ---- | ---------- |
67| noticeType | [NoticeType](#noticetype10) | 是   | 通知类型。 |
68| eventData  | string                      | 是   | 事件数据。 |
69
70**错误码:**
71
72以下错误码的详细介绍请参见[用户认证错误码](errorcode-useriam.md)。
73
74| 错误码ID | 错误信息                                |
75| -------- | --------------------------------------- |
76| 201      | Permission verification failed.         |
77| 202      | The caller is not a system application. |
78| 401      | Incorrect parameters. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.    |
79| 12500002 | General operation error.                |
80
81**示例:**
82
83```ts
84import { userAuth } from '@kit.UserAuthenticationKit';
85
86interface  EventData {
87  widgetContextId: number;
88  event: string;
89  version: string;
90  payload: PayLoad;
91}
92interface PayLoad {
93  type: Object[];
94}
95try {
96  const eventData : EventData = {
97    widgetContextId: 123456,
98    event: 'EVENT_AUTH_TYPE_READY',
99    version: '1',
100    payload: {
101      type: ['pin']
102    } as PayLoad,
103  };
104  const jsonEventData = JSON.stringify(eventData);
105  let noticeType = userAuth.NoticeType.WIDGET_NOTICE;
106  userAuth.sendNotice(noticeType, jsonEventData);
107  console.info('sendNotice success');
108} catch (error) {
109  console.error(`sendNotice catch error: ${JSON.stringify(error)}`);
110}
111```
112
113## UserAuthWidgetMgr<sup>10+</sup>
114
115组件管理接口,可将用身份认证控件注册到UserAuthWidgetMgr中,由UserAuthWidgetMgr进行管理、调度。
116
117### on<sup>10+</sup>
118
119on(type: 'command', callback: IAuthWidgetCallback): void
120
121身份认证控件订阅来自用户认证框架的命令。
122
123**系统能力**:SystemCapability.UserIAM.UserAuth.Core
124
125**系统接口**: 此接口为系统接口。
126
127**参数:**
128
129| 参数名   | 类型                                          | 必填 | 说明                                                         |
130| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
131| type     | 'command'                                     | 是   | 订阅事件类型,表明该事件用于用户认证框架向身份认证控件发送命令。 |
132| callback | [IAuthWidgetCallback](#iauthwidgetcallback10) | 是   | 组件管理接口的回调函数,用于用户认证框架向身份认证控件发送命令。 |
133
134**错误码:**
135
136以下错误码的详细介绍请参见[用户认证错误码](errorcode-useriam.md)。
137
138| 错误码ID | 错误信息                 |
139| -------- | ------------------------ |
140| 401      | Incorrect parameters. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
141| 12500002 | General operation error. |
142
143**示例:**
144
145```ts
146import { userAuth } from '@kit.UserAuthenticationKit';
147
148const userAuthWidgetMgrVersion = 1;
149try {
150  let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion);
151  console.info('get userAuthWidgetMgr instance success');
152  userAuthWidgetMgr.on('command', {
153    sendCommand(cmdData) {
154      console.info(`The cmdData is ${cmdData}`);
155    }
156  })
157  console.info('subscribe authentication event success');
158} catch (error) {
159  console.error(`userAuth widgetMgr catch error: ${JSON.stringify(error)}`);
160}
161```
162
163### off<sup>10+</sup>
164
165off(type: 'command', callback?: IAuthWidgetCallback): void
166
167身份认证控件取消订阅来自用户认证框架的命令。
168
169**系统能力**:SystemCapability.UserIAM.UserAuth.Core
170
171**系统接口**: 此接口为系统接口。
172
173**参数:**
174
175| 参数名   | 类型                                          | 必填 | 说明                                                         |
176| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
177| type     | 'command'                                     | 是   | 订阅事件类型,表明该事件用于用户认证框架向身份认证控件发送命令。 |
178| callback | [IAuthWidgetCallback](#iauthwidgetcallback10) | 否   | 组件管理接口的回调函数,用于用户认证框架向身份认证控件发送命令。 |
179
180**错误码:**
181
182以下错误码的详细介绍请参见[用户认证错误码](errorcode-useriam.md)。
183
184| 错误码ID | 错误信息                 |
185| -------- | ------------------------ |
186| 401      | Incorrect parameters. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
187| 12500002 | General operation error. |
188
189**示例:**
190
191```ts
192import { userAuth } from '@kit.UserAuthenticationKit';
193
194const userAuthWidgetMgrVersion = 1;
195try {
196  let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion);
197  console.info('get userAuthWidgetMgr instance success');
198  userAuthWidgetMgr.off('command', {
199    sendCommand(cmdData) {
200      console.info(`The cmdData is ${cmdData}`);
201    }
202  })
203  console.info('cancel subscribe authentication event success');
204} catch (error) {
205  console.error(`userAuth widgetMgr catch error: ${JSON.stringify(error)}`);
206}
207```
208
209## userAuth.getUserAuthWidgetMgr<sup>10+</sup>
210
211getUserAuthWidgetMgr(version: number): UserAuthWidgetMgr
212
213获取UserAuthWidgetMgr对象,用于执行用户身份认证。
214
215> **说明:**
216> 每个UserAuthInstance只能进行一次认证,若需要再次进行认证则需重新获取UserAuthInstance。
217
218**需要权限**:ohos.permission.SUPPORT_USER_AUTH
219
220**系统能力**:SystemCapability.UserIAM.UserAuth.Core
221
222**系统接口**: 此接口为系统接口。
223
224**参数:**
225
226| 参数名  | 类型   | 必填 | 说明                 |
227| ------- | ------ | ---- | -------------------- |
228| version | number | 是   | 表示认证组件的版本。 |
229
230**返回值:**
231
232| 类型                                      | 说明         |
233| ----------------------------------------- | ------------ |
234| [UserAuthWidgetMgr](#userauthwidgetmgr10) | 认证器对象。 |
235
236**错误码:**
237
238以下错误码的详细介绍请参见[用户认证错误码](errorcode-useriam.md)。
239
240| 错误码ID | 错误信息                                |
241| -------- | --------------------------------------- |
242| 201      | Permission verification failed.         |
243| 202      | The caller is not a system application. |
244| 401      | Incorrect parameters. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.                                     |
245| 12500002 | General operation error.                |
246
247**示例:**
248
249```ts
250import { userAuth } from '@kit.UserAuthenticationKit';
251
252let userAuthWidgetMgrVersion = 1;
253try {
254  let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion);
255  console.info('get userAuthWidgetMgr instance success');
256} catch (error) {
257  console.error(`userAuth widgetMgr catch error: ${JSON.stringify(error)}`);
258}
259```
260
261## IAuthWidgetCallback<sup>10+</sup>
262
263认证组件通过该回调获取用户认证框架发送的命令。
264
265### sendCommand<sup>10+</sup>
266
267sendCommand(cmdData: string): void
268
269回调函数,用于用户认证框架向组件发送命令。
270
271**系统能力**:SystemCapability.UserIAM.UserAuth.Core
272
273**系统接口**: 此接口为系统接口。
274
275**参数:**
276
277| 参数名  | 类型   | 必填 | 说明                               |
278| ------- | ------ | ---- | ---------------------------------- |
279| cmdData | string | 是   | 用户身份认证框架向控件发送的命令。 |
280
281**示例:**
282
283```ts
284import { userAuth } from '@kit.UserAuthenticationKit';
285
286const userAuthWidgetMgrVersion = 1;
287try {
288  let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion);
289  console.info('get userAuthWidgetMgr instance success');
290  userAuthWidgetMgr.on('command', {
291    sendCommand(cmdData) {
292      console.info(`The cmdData is ${cmdData}`);
293    }
294  })
295  console.info('subscribe authentication event success');
296} catch (error) {
297  console.error(`userAuth widgetMgr catch error: ${JSON.stringify(error)}`);
298}
299```
300
301## UserAuthType<sup>8+</sup>
302
303表示身份认证的凭据类型枚举。
304
305**系统能力**:SystemCapability.UserIAM.UserAuth.Core
306
307| 名称        | 值   | 说明       |
308| ----------- | ---- | ---------- |
309| PRIVATE_PIN<sup>14+</sup>  | 16   | 隐私口令。 |
310
311**示例:**
312
313发起用户认证,采用认证可信等级≥ATL3的隐私密码认证,获取认证结果:
314
315```ts
316import { BusinessError } from '@kit.BasicServicesKit';
317import { cryptoFramework } from '@kit.CryptoArchitectureKit';
318import { userAuth } from '@kit.UserAuthenticationKit';
319
320try {
321  const rand = cryptoFramework.createRandom();
322  const len: number = 16;
323  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
324  const authParam: userAuth.AuthParam = {
325    challenge: randData,
326    authType: [userAuth.UserAuthType.PRIVATE_PIN],
327    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
328  };
329  const widgetParam: userAuth.WidgetParam = {
330    title: '请输入密码',
331  };
332
333  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
334  console.info('get userAuth instance success');
335  // 需要调用UserAuthInstance的start()接口,启动认证后,才能通过onResult获取到认证结果。
336  userAuthInstance.on('result', {
337    onResult (result) {
338      console.info(`userAuthInstance callback result = ${JSON.stringify(result)}`);
339    }
340  });
341  console.info('auth on success');
342} catch (error) {
343  const err: BusinessError = error as BusinessError;
344  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
345}
346```