• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.userIAM.userAuth (User Authentication) (System API)
2
3The **userIAM.userAuth** module provides user authentication capabilities in identity authentication scenarios, such as device unlocking, payment, and app login.
4
5> **NOTE**
6>
7> - 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.
8> - This topic describes only the system APIs provided by the module. For details about its public APIs, see [@ohos.userIAM.userAuth (User Authentication)](js-apis-useriam-userauth.md).
9
10## Modules to Import
11
12```ts
13import { userAuth } from '@kit.UserAuthenticationKit';
14```
15
16## AuthParam<sup>10+</sup>
17
18Represents the user authentication parameters.
19
20**System capability**: SystemCapability.UserIAM.UserAuth.Core
21
22| Name          | Type                              | Mandatory| Description                                                        |
23| -------------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
24| userId<sup>16+</sup> | number | No  |ID of the user to be authenticated. The value is a positive integer greater than or equal to 0.|
25
26## WindowModeType<sup>10+</sup>
27
28Enumerates the window types of the authentication widget.
29
30**System capability**: SystemCapability.UserIAM.UserAuth.Core
31
32**System API**: This is a system API.
33
34| Name      | Value  | Description      |
35| ---------- | ---- | ---------- |
36| DIALOG_BOX | 1    | Dialog box.|
37| FULLSCREEN | 2    | Full screen.|
38
39## WidgetParam<sup>10+</sup>
40
41Represents the information presented on the user authentication page.
42
43**System capability**: SystemCapability.UserIAM.UserAuth.Core
44
45| Name                | Type                               | Mandatory| Description                                                        |
46| -------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ |
47| windowMode           | [WindowModeType](#windowmodetype10) | No  | Display format of the user authentication page. The default value is **WindowModeType.DIALOG_BOX**.<br>**System API**: This is a system API.|
48
49## NoticeType<sup>10+</sup>
50
51Defines the type of the user authentication notification.
52
53**System capability**: SystemCapability.UserIAM.UserAuth.Core
54
55**System API**: This is a system API.
56
57| Name         | Value  | Description                |
58| ------------- | ---- | -------------------- |
59| WIDGET_NOTICE | 1    | Notification from the user authentication widget.|
60
61## userAuth.sendNotice<sup>10+</sup>
62
63sendNotice(noticeType: NoticeType, eventData: string): void
64
65Sends a notification from the user authentication widget.
66
67**Required permissions**: ohos.permission.SUPPORT_USER_AUTH
68
69**System capability**: SystemCapability.UserIAM.UserAuth.Core
70
71**System API**: This is a system API.
72
73**Parameters**
74
75| Name    | Type                       | Mandatory| Description      |
76| ---------- | --------------------------- | ---- | ---------- |
77| noticeType | [NoticeType](#noticetype10) | Yes  | Notification type.|
78| eventData  | string                      | Yes  | Event data.|
79
80**Error codes**
81
82For details about the error codes, see [User Authentication Error Codes](errorcode-useriam.md).
83
84| ID| Error Message                               |
85| -------- | --------------------------------------- |
86| 201      | Permission verification failed.         |
87| 202      | The caller is not a system application. |
88| 401      | Incorrect parameters. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.    |
89| 12500002 | General operation error.                |
90
91**Example**
92
93```ts
94import { userAuth } from '@kit.UserAuthenticationKit';
95
96interface  EventData {
97  widgetContextId: number;
98  event: string;
99  version: string;
100  payload: PayLoad;
101}
102interface PayLoad {
103  type: Object[];
104}
105try {
106  const eventData : EventData = {
107    widgetContextId: 123456,
108    event: 'EVENT_AUTH_TYPE_READY',
109    version: '1',
110    payload: {
111      type: ['pin']
112    } as PayLoad,
113  };
114  const jsonEventData = JSON.stringify(eventData);
115  let noticeType = userAuth.NoticeType.WIDGET_NOTICE;
116  userAuth.sendNotice(noticeType, jsonEventData);
117  console.info('sendNotice success');
118} catch (error) {
119  console.error(`sendNotice catch error: ${JSON.stringify(error)}`);
120}
121```
122
123## UserAuthWidgetMgr<sup>10+</sup>
124
125Provides APIs for managing the user authentication widget. You can use the APIs to register the user authentication widget with UserAuthWidgetMgr for management and scheduling.
126
127### on<sup>10+</sup>
128
129on(type: 'command', callback: IAuthWidgetCallback): void
130
131Subscribes to commands from the user authentication framework for the user authentication widget.
132
133**System capability**: SystemCapability.UserIAM.UserAuth.Core
134
135**System API**: This is a system API.
136
137**Parameters**
138
139| Name  | Type                                         | Mandatory| Description                                                        |
140| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
141| type     | 'command'                                     | Yes  | Event type. The vlaue is **command**, which indicates the command sent from the user authentication framework to the user authentication widget. |
142| callback | [IAuthWidgetCallback](#iauthwidgetcallback10) | Yes  | Callback used to return the command from the user authentication framework to the user authentication widget.|
143
144**Error codes**
145
146For details about the error codes, see [User Authentication Error Codes](errorcode-useriam.md).
147
148| ID| Error Message                |
149| -------- | ------------------------ |
150| 401      | Incorrect parameters. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
151| 12500002 | General operation error. |
152
153**Example**
154
155```ts
156import { userAuth } from '@kit.UserAuthenticationKit';
157
158const userAuthWidgetMgrVersion = 1;
159try {
160  let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion);
161  console.info('get userAuthWidgetMgr instance success');
162  userAuthWidgetMgr.on('command', {
163    sendCommand(cmdData) {
164      console.info(`The cmdData is ${cmdData}`);
165    }
166  })
167  console.info('subscribe authentication event success');
168} catch (error) {
169  console.error(`userAuth widgetMgr catch error: ${JSON.stringify(error)}`);
170}
171```
172
173### off<sup>10+</sup>
174
175off(type: 'command', callback?: IAuthWidgetCallback): void
176
177Unsubscribes from commands sent from the user authentication framework.
178
179**System capability**: SystemCapability.UserIAM.UserAuth.Core
180
181**System API**: This is a system API.
182
183**Parameters**
184
185| Name  | Type                                         | Mandatory| Description                                                        |
186| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
187| type     | 'command'                                     | Yes  | Event type. The value is **command**, which indicates the command sent from the user authentication framework to the user authentication widget. |
188| callback | [IAuthWidgetCallback](#iauthwidgetcallback10) | No  | Callback to unregister.|
189
190**Error codes**
191
192For details about the error codes, see [User Authentication Error Codes](errorcode-useriam.md).
193
194| ID| Error Message                |
195| -------- | ------------------------ |
196| 401      | Incorrect parameters. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
197| 12500002 | General operation error. |
198
199**Example**
200
201```ts
202import { userAuth } from '@kit.UserAuthenticationKit';
203
204const userAuthWidgetMgrVersion = 1;
205try {
206  let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion);
207  console.info('get userAuthWidgetMgr instance success');
208  userAuthWidgetMgr.off('command', {
209    sendCommand(cmdData) {
210      console.info(`The cmdData is ${cmdData}`);
211    }
212  })
213  console.info('cancel subscribe authentication event success');
214} catch (error) {
215  console.error(`userAuth widgetMgr catch error: ${JSON.stringify(error)}`);
216}
217```
218
219## userAuth.getUserAuthWidgetMgr<sup>10+</sup>
220
221getUserAuthWidgetMgr(version: number): UserAuthWidgetMgr
222
223Obtains a **UserAuthWidgetMgr** instance for user authentication.
224
225> **NOTE**<br>
226> A **UserAuthInstance** instance can be used for an authentication only once.
227
228**Required permissions**: ohos.permission.SUPPORT_USER_AUTH
229
230**System capability**: SystemCapability.UserIAM.UserAuth.Core
231
232**System API**: This is a system API.
233
234**Parameters**
235
236| Name | Type  | Mandatory| Description                |
237| ------- | ------ | ---- | -------------------- |
238| version | number | Yes  | Version of the user authentication widget.|
239
240**Return value**
241
242| Type                                     | Description        |
243| ----------------------------------------- | ------------ |
244| [UserAuthWidgetMgr](#userauthwidgetmgr10) | **UserAuthWidgetMgr** instance obtained.|
245
246**Error codes**
247
248For details about the error codes, see [User Authentication Error Codes](errorcode-useriam.md).
249
250| ID| Error Message                               |
251| -------- | --------------------------------------- |
252| 201      | Permission verification failed.         |
253| 202      | The caller is not a system application. |
254| 401      | Incorrect parameters. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.                                     |
255| 12500002 | General operation error.                |
256
257**Example**
258
259```ts
260import { userAuth } from '@kit.UserAuthenticationKit';
261
262let userAuthWidgetMgrVersion = 1;
263try {
264  let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion);
265  console.info('get userAuthWidgetMgr instance success');
266} catch (error) {
267  console.error(`userAuth widgetMgr catch error: ${JSON.stringify(error)}`);
268}
269```
270
271## IAuthWidgetCallback<sup>10+</sup>
272
273Provides the callback for returning the commands sent from the user authentication framework to the user authentication widget.
274
275### sendCommand<sup>10+</sup>
276
277sendCommand(cmdData: string): void
278
279Called to return the command sent from the user authentication framework to the user authentication widget.
280
281**System capability**: SystemCapability.UserIAM.UserAuth.Core
282
283**System API**: This is a system API.
284
285**Parameters**
286
287| Name | Type  | Mandatory| Description                              |
288| ------- | ------ | ---- | ---------------------------------- |
289| cmdData | string | Yes  | Command sent from the user authentication framework to the user authentication widget.|
290
291**Example**
292
293```ts
294import { userAuth } from '@kit.UserAuthenticationKit';
295
296const userAuthWidgetMgrVersion = 1;
297try {
298  let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion);
299  console.info('get userAuthWidgetMgr instance success');
300  userAuthWidgetMgr.on('command', {
301    sendCommand(cmdData) {
302      console.info(`The cmdData is ${cmdData}`);
303    }
304  })
305  console.info('subscribe authentication event success');
306} catch (error) {
307  console.error(`userAuth widgetMgr catch error: ${JSON.stringify(error)}`);
308}
309```
310
311## UserAuthType<sup>8+</sup>
312
313Enumerates the types of credentials for identity authentication.
314
315**System capability**: SystemCapability.UserIAM.UserAuth.Core
316
317| Name       | Value  | Description      |
318| ----------- | ---- | ---------- |
319| PRIVATE_PIN<sup>14+</sup>  | 16   | Privacy password.|
320
321**Example**
322
323Initiate privacy PIN authentication with the authentication trust level greater than or equal to ATL3.
324
325```ts
326import { BusinessError } from '@kit.BasicServicesKit';
327import { cryptoFramework } from '@kit.CryptoArchitectureKit';
328import { userAuth } from '@kit.UserAuthenticationKit';
329
330try {
331  const rand = cryptoFramework.createRandom();
332  const len: number = 16;
333  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
334  const authParam: userAuth.AuthParam = {
335    challenge: randData,
336    authType: [userAuth.UserAuthType.PRIVATE_PIN],
337    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
338  };
339  const widgetParam: userAuth.WidgetParam = {
340    title: 'Enter password',
341  };
342
343  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
344  console.info('get userAuth instance success');
345  // The authentication result is returned by onResult() only after the authentication is started by start() of UserAuthInstance.
346  userAuthInstance.on('result', {
347    onResult (result) {
348      console.info(`userAuthInstance callback result = ${JSON.stringify(result)}`);
349    }
350  });
351  console.info('auth on success');
352} catch (error) {
353  const err: BusinessError = error as BusinessError;
354  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
355}
356```
357## UserAuthResultCode<sup>16+</sup>
358
359Enumerates the authentication result codes.
360
361**System capability**: SystemCapability.UserIAM.UserAuth.Core
362
363| Name | Value | Description |
364| ----------------------- | ------ | -------------------- |
365| AUTH_TOKEN_CHECK_FAILED | 12500015 | The authentication token is invalid. |
366| AUTH_TOKEN_EXPIRED | 12500016 | The authentication token has expired. |
367
368