1# Requesting User Authorization 2 3Before an application accesses user privacy information or use a system capability, for example, to obtain location information, access the Calendar, or use the camera to take a photo or record a video, the application needs to request user authorization. The permissions that must be authorized by users are user_grant permissions. 4 5The procedure for requesting user_grant permissions is as follows: 6 71. Declare the permissions required by your application in the configuration file. 8 92. Associate each object that requires a user_grant permission with the related permission. This lets the user know what operations need user authorization.<br> 10 For details about the preceding two steps, see [Declaring Permissions](declare-permissions.md). 11 123. Trigger user authorization via an API when the application in running needs to access the target object. The API first checks whether the user has granted the permission required. If no, a dialog box will be displayed to request authorization from the user. 13 144. Check the user authorization result, and allow the next step only after the user has granted the permission to the application. 15 16This topic elaborates steps 3 and 4. 17 18## Constraints 19 20- For a user_grant permission, show a rationale to the user in a UI element, clearly explaining why your application needs the permission. Based on the rationale, the user then determines whether to grant the permission. 21 22- Frequent pop-up windows may disturb user experience and are not recommended. If a user rejects the authorization, the window for requesting user authorization will not be displayed again. The application needs to provide information to guide the user to manually grant the permission in **Settings**. 23 24- The system permission pop-up window cannot be obscured. 25 26 The system permission pop-up window cannot be obscured by other components. The information in the pop-up window must be completely displayed so that the user can identify and complete authorization. 27 If the system permission pop-up window is displayed in the same position as another component, the system permission pop-up window takes precedence over the other component by default. 28 29- A check for the required permission is mandatory each time before the operation that requires the permission is performed. 30 31 You can use [checkAccessToken()](../../reference/apis-ability-kit/js-apis-abilityAccessCtrl.md#checkaccesstoken9) to check whether the user has granted specific permissions to your application. This API returns [PERMISSION_GRANTED](../../reference/apis-ability-kit/js-apis-abilityAccessCtrl.md#grantstatus) or [PERMISSION_DENIED](../../reference/apis-ability-kit/js-apis-abilityAccessCtrl.md#grantstatus). For details, see the example given below. 32 33- Each time before an API that requires a user_grant permission is called, use [requestPermissionsFromUser()](../../reference/apis-ability-kit/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) to check whether the user has already granted the permission. 34 35 After a permission is granted, the user may revoke the permission in **Settings**. Therefore, the previous authorization status cannot be persistent. 36 37- When requesting permissions using **onWindowStageCreate()**, the application needs to wait until the **loadContent()** or **setUIContent()** API is complete or call [requestPermissionsFromUser()](../../reference/apis-ability-kit/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) in **loadContent()** or **setUIContent()**. Otherwise, **requestPermissionsFromUser()** will fail before **Content** is loaded. 38 <!--RP1--><!--RP1End--> 39 40## How to Develop 41 42The following example steps you through on how to request the location permissions. 43 44**Figure 1** Requesting the location permissions 45 46 47 481. Request the ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION permissions. For details, see [Declaring Permissions](declare-permissions.md). 49 502. Check whether the user has granted the permissions. 51 52 Call [checkAccessToken()](../../reference/apis-ability-kit/js-apis-abilityAccessCtrl.md#checkaccesstoken9) to check whether the user has already granted the permissions that your application requires. If yes, the application can perform subsequent operations. Otherwise, user authorization is required. 53 54 ```ts 55 import { abilityAccessCtrl, bundleManager, Permissions } from '@kit.AbilityKit'; 56 import { BusinessError } from '@kit.BasicServicesKit'; 57 58 async function checkPermissionGrant(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> { 59 let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); 60 let grantStatus: abilityAccessCtrl.GrantStatus = abilityAccessCtrl.GrantStatus.PERMISSION_DENIED; 61 62 // Obtain the token ID of the application. 63 let tokenId: number = 0; 64 try { 65 let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION); 66 let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo; 67 tokenId = appInfo.accessTokenId; 68 } catch (error) { 69 const err: BusinessError = error as BusinessError; 70 console.error(`Failed to get bundle info for self. Code is ${err.code}, message is ${err.message}`); 71 } 72 73 // Check whether the user has granted the permission. 74 try { 75 grantStatus = await atManager.checkAccessToken(tokenId, permission); 76 } catch (error) { 77 const err: BusinessError = error as BusinessError; 78 console.error(`Failed to check access token. Code is ${err.code}, message is ${err.message}`); 79 } 80 81 return grantStatus; 82 } 83 84 async function checkPermissions(): Promise<void> { 85 let grantStatus1: boolean = await checkPermissionGrant('ohos.permission.LOCATION') === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED;// Obtain the status of the ohos.permission.LOCATION permission. 86 let grantStatus2: boolean = await checkPermissionGrant('ohos.permission.APPROXIMATELY_LOCATION') === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED;// Obtain the status of the ohos.permission.APPROXIMATELY_LOCATION permission. 87 // The ohos.permission.LOCATION permission must be requested with the ohos.permission.APPROXIMATELY_LOCATION permission together or after the ohos.permission.APPROXIMATELY_LOCATION permission is available. 88 if (grantStatus2 && !grantStatus1) { 89 // Request the ohos.permission.LOCATION permission. 90 } else if (!grantStatus1 && !grantStatus2) { 91 // Request the ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION permissions, or request the ohos.permission.APPROXIMATELY_LOCATION permission. 92 } else { 93 // If the user grants the permission, the application can access location information. 94 } 95 } 96 ``` 97 983. Request user authorization when your application needs to access location information. 99 100 Call [requestPermissionsFromUser()](../../reference/apis-ability-kit/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) to request user authorization. You can specify a list of permissions, such as the permission to access the location, Calendar, camera, or microphone, in the **Array\<Permissions>** parameter of this API. The user can grant or deny the permissions. 101 102 You can have [requestPermissionsFromUser()](../../reference/apis-ability-kit/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) called in **onWindowStageCreate()** of the UIAbility to dynamically request user authorization, or request user authorization on the UI based on service requirements. 103 104 When requesting permissions using **onWindowStageCreate()**, the application needs to wait until the **loadContent()** or **setUIContent()** API is complete or call [requestPermissionsFromUser()](../../reference/apis-ability-kit/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) in **loadContent()** or **setUIContent()**. Otherwise, **requestPermissionsFromUser()** will fail before **Content** is loaded. 105 106 <!--RP1--><!--RP1End--> 107 108 <!--RP2--> 109 - Sample code for requesting user authorization using UIAbility 110 111 ```ts 112 import { abilityAccessCtrl, common, Permissions, UIAbility } from '@kit.AbilityKit'; 113 import { window } from '@kit.ArkUI'; 114 import { BusinessError } from '@kit.BasicServicesKit'; 115 116 const permissions: Array<Permissions> = ['ohos.permission.LOCATION','ohos.permission.APPROXIMATELY_LOCATION']; 117 function reqPermissionsFromUser(permissions: Array<Permissions>, context: common.UIAbilityContext): void { 118 let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); 119 // Determine whether to display a user authorization dialog box based on the return value of requestPermissionsFromUser. 120 atManager.requestPermissionsFromUser(context, permissions).then((data) => { 121 let grantStatus: Array<number> = data.authResults; 122 let length: number = grantStatus.length; 123 for (let i = 0; i < length; i++) { 124 if (grantStatus[i] === 0) { 125 // If the user grants the permission, the application can perform the subsequent operation. 126 } else { 127 // If the user denies the permission, display a message indicating that user authorization is required, and direct the user to set the permission in the Settings page. 128 return; 129 } 130 } 131 // The authorization is successful. 132 }).catch((err: BusinessError) => { 133 console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`); 134 }) 135 } 136 export default class EntryAbility extends UIAbility { 137 onWindowStageCreate(windowStage: window.WindowStage): void { 138 // ... 139 windowStage.loadContent('pages/Index', (err, data) => { 140 reqPermissionsFromUser(permissions, this.context); 141 // ... 142 }); 143 } 144 145 // ... 146 } 147 ``` 148 149 - Sample code for requesting user authorization on the UI 150 151 ```ts 152 import { abilityAccessCtrl, common, Permissions } from '@kit.AbilityKit'; 153 import { BusinessError } from '@kit.BasicServicesKit'; 154 155 const permissions: Array<Permissions> = ['ohos.permission.LOCATION','ohos.permission.APPROXIMATELY_LOCATION']; 156 function reqPermissionsFromUser(permissions: Array<Permissions>, context: common.UIAbilityContext): void { 157 let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); 158 // Determine whether to display a user authorization dialog box based on the return value of requestPermissionsFromUser. 159 atManager.requestPermissionsFromUser(context, permissions).then((data) => { 160 let grantStatus: Array<number> = data.authResults; 161 let length: number = grantStatus.length; 162 for (let i = 0; i < length; i++) { 163 if (grantStatus[i] === 0) { 164 // If the user grants the permission, the application can perform the subsequent operation. 165 } else { 166 // If the user denies the permission, display a message indicating that user authorization is required, and direct the user to set the permission in the Settings page. 167 return; 168 } 169 } 170 // The authorization is successful. 171 }).catch((err: BusinessError) => { 172 console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`); 173 }) 174 } 175 176 @Entry 177 @Component 178 struct Index { 179 aboutToAppear() { 180 const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; 181 reqPermissionsFromUser(permissions, context); 182 } 183 184 build() { 185 // ... 186 } 187 } 188 ``` 189 <!--RP2End--> 190 1914. Perform subsequent operations based on the authorization result. 192 193 After [requestPermissionsFromUser()](../../reference/apis-ability-kit/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) is called, the application waits for the user authorization result. If the user grants the permission, the application can perform the subsequent operation. Otherwise, display a message indicating that user authorization is required, and direct the user to set the permission on the **Settings** page.<!--RP3--> 194 195 Path: **Settings**\> **Privacy**\> **Permission manager**\> **Apps**\> Target app<!--RP3End--> 196