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