1# Initiating User Authentication 2 3<!--Kit: User Authentication Kit--> 4<!--Subsystem: UserIAM--> 5<!--Owner: @WALL_EYE--> 6<!--SE: @lichangting518--> 7<!--TSE: @jane_lz--> 8 9A user authentication is required before an application accesses a critical functionality or sensitive data. This topic walks you through the process. 10 11## Available APIs 12 13For details about the parameters, return values, and error codes, see [User Authentication](../../reference/apis-user-authentication-kit/js-apis-useriam-userauth.md#userauthgetuserauthinstance10). 14 15| API| Description| 16| -------- | -------- | 17| getUserAuthInstance(authParam: AuthParam, widgetParam: WidgetParam): UserAuthInstance | Obtains a **UserAuthInstance** object for user authentication. The unified [user authentication widget](#user-authentication-widget) is also supported.| 18| on(type: 'result', callback: IAuthCallback): void | Subscribes to the user authentication result.| 19| off(type: 'result', callback?: IAuthCallback): void | Unsubscribes from the user authentication result.| 20| start(): void | Starts user authentication.| 21 22## User Authentication Widget 23 24The system provides a unified user authentication widget, which stands out with following features: 25 26- The user authentication widget identifies and authenticates user information and returns the authentication result to the application. The overall process is secure and controllable. 27 28- The widget comes with a unified UI component style to elevate user experience. 29 30The 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. 31 32<!--RP1--> 33 34<!--RP1End--> 35 36- ①: Title (**WidgetParam.title**) of the user authentication page, which cannot exceed 500 characters. You can set the title based on actual requirements. 37<!--RP2--> 38- ②: Text on the navigation button (**WidgetParam.navigationButtonText**), which cannot exceed 60 characters. It can be configured only in single fingerprint or facial authentication scenarios in API versions 10 to 17. Since API version 18, it can also be configured in the combined fingerprint and facial authentication. 39 40 If biometric authentication fails, a button is displayed. The user can tap the button to switch to custom authentication.<!--RP2End--> 41 42<!--Del--> 43- The following shows the display modes (**WidgetParam.windowMode**) of the user authentication widget. 44 45 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). 46 47 Currently, the full screen mode is available only for system applications. 48 49  50<!--DelEnd--> 51 52The user authentication widget supports the following types of authentication: 53 54- Lock screen password authentication 55 56- Facial authentication 57 58- Fingerprint authentication 59 60- Facial + lock screen password authentication 61 62- Fingerprint + lock screen password authentication 63 64- Facial + fingerprint + lock screen password authentication 65 66- Facial authentication + custom navigation button 67 68- Fingerprint authentication + custom navigation button 69 70- Facial authentication + fingerprint authentication + custom navigation button<sup>18+</sup> 71 72## How to Develop 73 741. 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). 75 762. 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. 77 783. Use [UserAuthInstance.on](../../reference/apis-user-authentication-kit/js-apis-useriam-userauth.md#on10) to subscribe to the authentication result. 79 804. 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). If the authentication is successful, [UserAuthType](../../reference/apis-user-authentication-kit/js-apis-useriam-userauth.md#userauthtype8) and token information (**AuthToken**) are returned. 81 82**Example 1** 83 84 Initiate facial authentication and lock screen password authentication at ATL3 or higher. 85 86```ts 87// API version 10 88import { BusinessError } from '@kit.BasicServicesKit'; 89import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 90import { userAuth } from '@kit.UserAuthenticationKit'; 91 92try { 93 const rand = cryptoFramework.createRandom(); 94 const len: number = 16; // Generate a 16-byte random number. 95 let randData: Uint8Array | null = null; 96 let retryCount = 0; 97 while(retryCount < 3){ 98 randData = rand?.generateRandomSync(len)?.data; 99 if(randData){ 100 break; 101 } 102 retryCount++; 103 } 104 if(!randData){ 105 return; 106 } 107 // Set authentication parameters. 108 const authParam: userAuth.AuthParam = { 109 challenge: randData, 110 authType: [userAuth.UserAuthType.PIN, userAuth.UserAuthType.FACE], 111 authTrustLevel: userAuth.AuthTrustLevel.ATL3, 112 }; 113 // Set the authentication page. 114 const widgetParam: userAuth.WidgetParam = { 115 title: 'Verify identity', 116 }; 117 // Obtain an authentication object. 118 const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam); 119 console.info('get userAuth instance success'); 120 // Subscribe to the authentication result. 121 userAuthInstance.on('result', { 122 onResult(result) { 123 console.info(`userAuthInstance callback result: ${JSON.stringify(result)}`); 124 // Unsubscribe from the authentication result if required. 125 userAuthInstance.off('result'); 126 } 127 }); 128 console.info('auth on success'); 129 userAuthInstance.start(); 130 console.info('auth start success'); 131} catch (error) { 132 const err: BusinessError = error as BusinessError; 133 console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`); 134} 135``` 136**Example 2** 137 138Initiate facial authentication at ATL3 or higher, and enable the device unlock result to be reused for the same type of authentication within the specified time. 139 140```ts 141// API version 10 142import { BusinessError } from '@kit.BasicServicesKit'; 143import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 144import { userAuth } from '@kit.UserAuthenticationKit'; 145 146// Set authentication parameters. 147let reuseUnlockResult: userAuth.ReuseUnlockResult = { 148 reuseMode: userAuth.ReuseMode.AUTH_TYPE_RELEVANT, 149 reuseDuration: userAuth.MAX_ALLOWABLE_REUSE_DURATION, 150} 151try { 152 const rand = cryptoFramework.createRandom(); 153 const len: number = 16; 154 let randData: Uint8Array | null = null; 155 let retryCount = 0; 156 while(retryCount < 3){ 157 randData = rand?.generateRandomSync(len)?.data; 158 if(randData){ 159 break; 160 } 161 retryCount++; 162 } 163 if(!randData){ 164 return; 165 } 166 const authParam: userAuth.AuthParam = { 167 challenge: randData, 168 authType: [userAuth.UserAuthType.FACE], 169 authTrustLevel: userAuth.AuthTrustLevel.ATL3, 170 reuseUnlockResult: reuseUnlockResult, 171 }; 172 // Set the authentication page. 173 const widgetParam: userAuth.WidgetParam = { 174 title: 'Verify identity', 175 }; 176 // Obtain an authentication object. 177 const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam); 178 console.info('get userAuth instance success'); 179 // Subscribe to the authentication result. 180 userAuthInstance.on('result', { 181 onResult(result) { 182 console.info(`userAuthInstance callback result: ${JSON.stringify(result)}`); 183 // Unsubscribe from the authentication result if required. 184 userAuthInstance.off('result'); 185 } 186 }); 187 console.info('auth on success'); 188 userAuthInstance.start(); 189 console.info('auth start success'); 190} catch (error) { 191 const err: BusinessError = error as BusinessError; 192 console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`); 193} 194``` 195**Example 3** 196 197Initiate facial authentication at ATL3 or higher, and enable the device unlock result to be reused for any type of authentication within the maximum authentication validity of any application. 198 199```ts 200// API version 14 201import { BusinessError } from '@kit.BasicServicesKit'; 202import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 203import { userAuth } from '@kit.UserAuthenticationKit'; 204 205// Set authentication parameters. 206let reuseUnlockResult: userAuth.ReuseUnlockResult = { 207 reuseMode: userAuth.ReuseMode.CALLER_IRRELEVANT_AUTH_TYPE_RELEVANT, 208 reuseDuration: userAuth.MAX_ALLOWABLE_REUSE_DURATION, 209} 210try { 211 const rand = cryptoFramework.createRandom(); 212 const len: number = 16; 213 let randData: Uint8Array | null = null; 214 let retryCount = 0; 215 while(retryCount < 3){ 216 randData = rand?.generateRandomSync(len)?.data; 217 if(randData){ 218 break; 219 } 220 retryCount++; 221 } 222 if(!randData){ 223 return; 224 } 225 const authParam: userAuth.AuthParam = { 226 challenge: randData, 227 authType: [userAuth.UserAuthType.FACE], 228 authTrustLevel: userAuth.AuthTrustLevel.ATL3, 229 reuseUnlockResult: reuseUnlockResult, 230 }; 231 // Set the authentication page. 232 const widgetParam: userAuth.WidgetParam = { 233 title: 'Verify identity', 234 }; 235 // Obtain an authentication object. 236 const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam); 237 console.info('get userAuth instance success'); 238 // Subscribe to the authentication result. 239 userAuthInstance.on('result', { 240 onResult(result) { 241 console.info(`userAuthInstance callback result: ${JSON.stringify(result)}`); 242 // Unsubscribe from the authentication result if required. 243 userAuthInstance.off('result'); 244 } 245 }); 246 console.info('auth on success'); 247 userAuthInstance.start(); 248 console.info('auth start success'); 249} catch (error) { 250 const err: BusinessError = error as BusinessError; 251 console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`); 252} 253``` 254 255**Example 4** 256 257Start the user authentication widget in modal application mode. 258 259```ts 260// API version 18 261import { BusinessError } from '@kit.BasicServicesKit'; 262import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 263import { userAuth } from '@kit.UserAuthenticationKit'; 264 265try { 266 const rand = cryptoFramework.createRandom(); 267 const len: number = 16; 268 let randData: Uint8Array | null = null; 269 let retryCount = 0; 270 while(retryCount < 3){ 271 randData = rand?.generateRandomSync(len)?.data; 272 if(randData){ 273 break; 274 } 275 retryCount++; 276 } 277 if(!randData){ 278 return; 279 } 280 const authParam: userAuth.AuthParam = { 281 challenge: randData, 282 authType: [userAuth.UserAuthType.PIN], 283 authTrustLevel: userAuth.AuthTrustLevel.ATL3, 284 }; 285 const widgetParam: userAuth.WidgetParam = { 286 title: 'Enter password', 287 uiContext: this.getUIContext().getHostContext(), 288 }; 289 const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam); 290 console.info('get userAuth instance success'); 291 // The authentication result is returned by onResult() only after the authentication is started by start() of UserAuthInstance. 292 userAuthInstance.on('result', { 293 onResult (result) { 294 console.info(`userAuthInstance callback result = ${JSON.stringify(result)}`); 295 } 296 }); 297 console.info('auth on success'); 298 userAuthInstance.start(); 299 console.info('auth start success'); 300} catch (error) { 301 const err: BusinessError = error as BusinessError; 302 console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`); 303} 304``` 305