1# Initiating User Authentication
2
3
4A user authentication is required before an application accesses a critical functionality or sensitive data. This topic walks you through the process.
5
6
7## Available APIs
8
9For details about the parameters, return values, and error codes, see [User Authentication](../../reference/apis-user-authentication-kit/js-apis-useriam-userauth.md#userauthgetuserauthinstance10).
10
11| API| Description|
12| -------- | -------- |
13| getUserAuthInstance(authParam: AuthParam, widgetParam: WidgetParam): UserAuthInstance | Obtains a **UserAuthInstance** object for user authentication. The unified [user authentication widget](#user-authentication-widget) is also supported.|
14| on(type: 'result', callback: IAuthCallback): void | Subscribes to the user authentication result.|
15| off(type: 'result', callback?: IAuthCallback): void | Unsubscribes from the user authentication result.|
16| start(): void | Starts user authentication.|
17
18
19## User Authentication Widget
20
21The system provides a unified user authentication widget, which stands out with following features:
22
23- The user authentication widget identifies and authenticates user information and returns the authentication result to the application. The overall process is secure and controllable.
24
25- The widget comes with a unified UI component style to elevate user experience.
26
27The following figure shows the style of the user authentication widget, which can be set via the [WidgetParam](../../reference/apis-user-authentication-kit/js-apis-useriam-userauth.md#widgetparam10) parameter.
28
29<!--RP1-->
30![](figures/user-authentication-widget.png)
31<!--RP1End-->
32
33- ①: Title (**WidgetParam.title**) of the user authentication page, which cannot exceed 500 characters. You can set the title based on actual requirements.
34
35- ②: Text on the navigation button (**WidgetParam.navigationButtonText**), which cannot exceed 60 characters. This parameter can be set only for a single fingerprint or facial authentication.
36
37  If biometric authentication fails, the authentication widget button is displayed. You can click this button to apply custom authentication.
38
39<!--Del-->
40- The following shows the display modes (**WidgetParam.windowMode**) of the user authentication widget.
41
42  The user authentication widget provides two display modes: dialog box (default mode, as shown in figure on the left) and full screen (as shown in the figure on the right).
43
44  Currently, the full screen mode is available only for system applications.
45
46  ![](figures/widget_display_modes.png)
47<!--DelEnd-->
48
49The user authentication widget supports the following types of authentication:
50
51- Lock screen password authentication
52
53- Facial authentication
54
55- Fingerprint authentication
56
57- Facial + lock screen password authentication
58
59- Fingerprint + lock screen password authentication
60
61- Facial + fingerprint + lock screen password authentication
62
63> **NOTE**
64> Currently, the text on the navigation button (**WidgetParam.navigationButtonText**) can be set only for a single fingerprint or facial authentication.
65
66
67## How to Develop
68
691. Check that the application has the ohos.permission.ACCESS_BIOMETRIC permission. For details about how to request permissions, see [Requesting Permissions](prerequisites.md#requesting-permissions).
70
712. Set [AuthParam](../../reference/apis-user-authentication-kit/js-apis-useriam-userauth.md#authparam10) (including the challenge, [UserAuthType](../../reference/apis-user-authentication-kit/js-apis-useriam-userauth.md#userauthtype8), and [AuthTrustLevel](../../reference/apis-user-authentication-kit/js-apis-useriam-userauth.md#authtrustlevel8)), configure [WidgetParam](../../reference/apis-user-authentication-kit/js-apis-useriam-userauth.md#widgetparam10), and use [getUserAuthInstance](../../reference/apis-user-authentication-kit/js-apis-useriam-userauth.md#userauthgetuserauthinstance10) to obtain a **UserAuthInstance** instance.
72
733. Use [UserAuthInstance.on](../../reference/apis-user-authentication-kit/js-apis-useriam-userauth.md#on10) to subscribe to the authentication result.
74
754. Use [UserAuthInstance.start](../../reference/apis-user-authentication-kit/js-apis-useriam-userauth.md#start10) to start authentication. The authentication result [UserAuthResult](../../reference/apis-user-authentication-kit/js-apis-useriam-userauth.md#userauthresult10) is returned through [IAuthCallback](../../reference/apis-user-authentication-kit/js-apis-useriam-userauth.md#iauthcallback10).
76   If the authentication is successful, [UserAuthType](../../reference/apis-user-authentication-kit/js-apis-useriam-userauth.md#userauthtype8) and token information (**AuthToken**) are returned.
77
78**Example 1**
79
80 Initiate facial authentication and lock screen password authentication with the authentication trust level greater than or equal to ATL3.
81
82```ts
83// API version 10
84import { BusinessError } from '@kit.BasicServicesKit';
85import { cryptoFramework } from '@kit.CryptoArchitectureKit';
86import { userAuth } from '@kit.UserAuthenticationKit';
87
88try {
89  const rand = cryptoFramework.createRandom();
90  const len: number = 16; // Generate a 16-byte random number.
91  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
92  // Set authentication parameters.
93  const authParam: userAuth.AuthParam = {
94    challenge: randData,
95    authType: [userAuth.UserAuthType.PIN, userAuth.UserAuthType.FACE],
96    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
97  };
98  // Set the authentication page.
99  const widgetParam: userAuth.WidgetParam = {
100    title: 'Verify identity',
101  };
102  // Obtain a UserAuthInstance object.
103  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
104  console.info('get userAuth instance success');
105  // Subscribe to the authentication result.
106  userAuthInstance.on('result', {
107    onResult(result) {
108      console.info(`userAuthInstance callback result: ${JSON.stringify(result)}`);
109      // Unsubscribe from the authentication result if required.
110      userAuthInstance.off('result');
111    }
112  });
113  console.info('auth on success');
114  userAuthInstance.start();
115  console.info('auth start success');
116} catch (error) {
117  const err: BusinessError = error as BusinessError;
118  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
119}
120```
121**Example 2**
122
123Initiate facial authentication with the authentication trust level greater than or equal to ATL3, and enable the device unlock result to be reused for the same type of authentication within the specified time.
124
125```ts
126// API version 10
127import { BusinessError } from  '@kit.BasicServicesKit';
128import { cryptoFramework } from '@kit.CryptoArchitectureKit';
129import { userAuth } from '@kit.UserAuthenticationKit';
130
131// Set authentication parameters.
132let reuseUnlockResult: userAuth.ReuseUnlockResult = {
133  reuseMode: userAuth.ReuseMode.AUTH_TYPE_RELEVANT,
134  reuseDuration: userAuth.MAX_ALLOWABLE_REUSE_DURATION,
135}
136try {
137  const rand = cryptoFramework.createRandom();
138  const len: number = 16;
139  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
140  const authParam: userAuth.AuthParam = {
141    challenge: randData,
142    authType: [userAuth.UserAuthType.FACE],
143    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
144    reuseUnlockResult: reuseUnlockResult,
145  };
146  // Set the authentication page.
147  const widgetParam: userAuth.WidgetParam = {
148    title: 'Verify identity',
149  };
150  // Obtain a UserAuthInstance object.
151  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
152  console.info('get userAuth instance success');
153  // Subscribe to the authentication result.
154  userAuthInstance.on('result', {
155    onResult(result) {
156      console.info(`userAuthInstance callback result: ${JSON.stringify(result)}`);
157      // Unsubscribe from the authentication result if required.
158      userAuthInstance.off('result');
159    }
160  });
161  console.info('auth on success');
162  userAuthInstance.start();
163  console.info('auth start success');
164} catch (error) {
165  const err: BusinessError = error as BusinessError;
166  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
167}
168```
169**Example 3**
170
171Initiate facial authentication with the authentication trust level greater than or equal to ATL3, and enable the device unlock result to be reused for any type of authentication within the maximum authentication validity of any application.
172
173```ts
174// API version 14
175import { BusinessError } from  '@kit.BasicServicesKit';
176import { cryptoFramework } from '@kit.CryptoArchitectureKit';
177import { userAuth } from '@kit.UserAuthenticationKit';
178
179// Set authentication parameters.
180let reuseUnlockResult: userAuth.ReuseUnlockResult = {
181  reuseMode: userAuth.ReuseMode.CALLER_IRRELEVANT_AUTH_TYPE_RELEVANT,
182  reuseDuration: userAuth.MAX_ALLOWABLE_REUSE_DURATION,
183}
184try {
185  const rand = cryptoFramework.createRandom();
186  const len: number = 16;
187  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
188  const authParam: userAuth.AuthParam = {
189    challenge: randData,
190    authType: [userAuth.UserAuthType.FACE],
191    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
192    reuseUnlockResult: reuseUnlockResult,
193  };
194  // Set the authentication page.
195  const widgetParam: userAuth.WidgetParam = {
196    title: 'Verify identity',
197  };
198  // Obtain a UserAuthInstance object.
199  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
200  console.info('get userAuth instance success');
201  // Subscribe to the authentication result.
202  userAuthInstance.on('result', {
203    onResult(result) {
204      console.info(`userAuthInstance callback result: ${JSON.stringify(result)}`);
205      // Unsubscribe from the authentication result if required.
206      userAuthInstance.off('result');
207    }
208  });
209  console.info('auth on success');
210  userAuthInstance.start();
211  console.info('auth start success');
212} catch (error) {
213  const err: BusinessError = error as BusinessError;
214  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
215}
216```
217
218
219
220
221