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 30 31 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  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> 65> Currently, the text on the navigation button (**WidgetParam.navigationButtonText**) can be set only for a single fingerprint or facial authentication. 66 67 68## How to Develop 69 701. 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). 71 722. 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. 73 743. Use [UserAuthInstance.on](../../reference/apis-user-authentication-kit/js-apis-useriam-userauth.md#on10) to subscribe to the authentication result. 75 764. 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). 77 If the authentication is successful, [UserAuthType](../../reference/apis-user-authentication-kit/js-apis-useriam-userauth.md#userauthtype8) and token information (**AuthToken**) are returned. 78 79**Example 1** 80 81 Initiate facial authentication and lock screen password authentication with the authentication trust level greater than or equal to ATL3. 82 83```ts 84// API version 10 85import { BusinessError } from '@kit.BasicServicesKit'; 86import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 87import { userAuth } from '@kit.UserAuthenticationKit'; 88 89try { 90 const rand = cryptoFramework.createRandom(); 91 const len: number = 16; // Generate a 16-byte random number. 92 const randData: Uint8Array = rand?.generateRandomSync(len)?.data; 93 // Set authentication parameters. 94 const authParam: userAuth.AuthParam = { 95 challenge: randData, 96 authType: [userAuth.UserAuthType.PIN, userAuth.UserAuthType.FACE], 97 authTrustLevel: userAuth.AuthTrustLevel.ATL3, 98 }; 99 // Set the authentication page. 100 const widgetParam: userAuth.WidgetParam = { 101 title: 'Verify identity', 102 }; 103 // Obtain a UserAuthInstance object. 104 const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam); 105 console.info('get userAuth instance success'); 106 // Subscribe to the authentication result. 107 userAuthInstance.on('result', { 108 onResult(result) { 109 console.info(`userAuthInstance callback result: ${JSON.stringify(result)}`); 110 // Unsubscribe from the authentication result if required. 111 userAuthInstance.off('result'); 112 } 113 }); 114 console.info('auth on success'); 115 userAuthInstance.start(); 116 console.info('auth start success'); 117} catch (error) { 118 const err: BusinessError = error as BusinessError; 119 console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`); 120} 121``` 122**Example 2** 123 124Initiate 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. 125 126```ts 127// API version 10 128import { BusinessError } from '@kit.BasicServicesKit'; 129import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 130import { userAuth } from '@kit.UserAuthenticationKit'; 131 132// Set authentication parameters. 133let reuseUnlockResult: userAuth.ReuseUnlockResult = { 134 reuseMode: userAuth.ReuseMode.AUTH_TYPE_RELEVANT, 135 reuseDuration: userAuth.MAX_ALLOWABLE_REUSE_DURATION, 136} 137try { 138 const rand = cryptoFramework.createRandom(); 139 const len: number = 16; 140 const randData: Uint8Array = rand?.generateRandomSync(len)?.data; 141 const authParam: userAuth.AuthParam = { 142 challenge: randData, 143 authType: [userAuth.UserAuthType.FACE], 144 authTrustLevel: userAuth.AuthTrustLevel.ATL3, 145 reuseUnlockResult: reuseUnlockResult, 146 }; 147 // Set the authentication page. 148 const widgetParam: userAuth.WidgetParam = { 149 title: 'Verify identity', 150 }; 151 // Obtain a UserAuthInstance object. 152 const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam); 153 console.info('get userAuth instance success'); 154 // Subscribe to the authentication result. 155 userAuthInstance.on('result', { 156 onResult(result) { 157 console.info(`userAuthInstance callback result: ${JSON.stringify(result)}`); 158 // Unsubscribe from the authentication result if required. 159 userAuthInstance.off('result'); 160 } 161 }); 162 console.info('auth on success'); 163 userAuthInstance.start(); 164 console.info('auth start success'); 165} catch (error) { 166 const err: BusinessError = error as BusinessError; 167 console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`); 168} 169``` 170**Example 3** 171 172Initiate 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. 173 174```ts 175// API version 14 176import { BusinessError } from '@kit.BasicServicesKit'; 177import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 178import { userAuth } from '@kit.UserAuthenticationKit'; 179 180// Set authentication parameters. 181let reuseUnlockResult: userAuth.ReuseUnlockResult = { 182 reuseMode: userAuth.ReuseMode.CALLER_IRRELEVANT_AUTH_TYPE_RELEVANT, 183 reuseDuration: userAuth.MAX_ALLOWABLE_REUSE_DURATION, 184} 185try { 186 const rand = cryptoFramework.createRandom(); 187 const len: number = 16; 188 const randData: Uint8Array = rand?.generateRandomSync(len)?.data; 189 const authParam: userAuth.AuthParam = { 190 challenge: randData, 191 authType: [userAuth.UserAuthType.FACE], 192 authTrustLevel: userAuth.AuthTrustLevel.ATL3, 193 reuseUnlockResult: reuseUnlockResult, 194 }; 195 // Set the authentication page. 196 const widgetParam: userAuth.WidgetParam = { 197 title: 'Verify identity', 198 }; 199 // Obtain a UserAuthInstance object. 200 const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam); 201 console.info('get userAuth instance success'); 202 // Subscribe to the authentication result. 203 userAuthInstance.on('result', { 204 onResult(result) { 205 console.info(`userAuthInstance callback result: ${JSON.stringify(result)}`); 206 // Unsubscribe from the authentication result if required. 207 userAuthInstance.off('result'); 208 } 209 }); 210 console.info('auth on success'); 211 userAuthInstance.start(); 212 console.info('auth start success'); 213} catch (error) { 214 const err: BusinessError = error as BusinessError; 215 console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`); 216} 217``` 218 219**Example 4** 220 221Perform user identity authentication in modal application mode. 222 223```ts 224// API version 16 225import { BusinessError } from '@kit.BasicServicesKit'; 226import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 227import { userAuth } from '@kit.UserAuthenticationKit'; 228 229try { 230 const rand = cryptoFramework.createRandom(); 231 const len: number = 16; 232 const randData: Uint8Array = rand?.generateRandomSync(len)?.data; 233 const authParam: userAuth.AuthParam = { 234 challenge: randData, 235 authType: [userAuth.UserAuthType.PIN], 236 authTrustLevel: userAuth.AuthTrustLevel.ATL3, 237 }; 238 const widgetParam: userAuth.WidgetParam = { 239 title: 'Enter password', 240 uiContext: this.getUIContext().getHostContext(), 241 }; 242 const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam); 243 console.info('get userAuth instance success'); 244 // The authentication result is returned by onResult() only after the authentication is started by start() of UserAuthInstance. 245 userAuthInstance.on('result', { 246 onResult (result) { 247 console.info(`userAuthInstance callback result = ${JSON.stringify(result)}`); 248 } 249 }); 250 console.info('auth on success'); 251} catch (error) { 252 const err: BusinessError = error as BusinessError; 253 console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`); 254} 255``` 256