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- A check for the required permission is mandatory each time before the operation that requires the permission is performed.
21  
22  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.
23
24- 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.
25
26  After a permission is granted, the user may revoke the permission in **Settings**. Therefore, the previous authorization status cannot be persistent.
27
28- 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.
29
30- 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**.
31
32- The system permission pop-up window cannot be obscured.
33
34  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.
35  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.
36
37## How to Develop
38
39The following example steps you through on how to request the permission for using the microphone.
40
41**Figure** Requesting user authorization
42
43![](figures/request_user_authorization.png)
44
451. Declare the ohos.permission.MICROPHONE permission in the configuration file. For details, see [Declaring Permissions](declare-permissions.md).
46
472. Check whether the user has granted the permission.
48
49   Use [checkAccessToken()](../../reference/apis-ability-kit/js-apis-abilityAccessCtrl.md#checkaccesstoken9) to check whether the user has already granted the permission that your application requires. If yes, the application can use the microphone. Otherwise, user authorization is required.
50
51   ```ts
52   import { abilityAccessCtrl, bundleManager, Permissions } from '@kit.AbilityKit';
53   import { BusinessError } from '@kit.BasicServicesKit';
54   
55   const permissions: Array<Permissions> = ['ohos.permission.MICROPHONE'];
56   
57   async function checkPermissionGrant(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
58     let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
59     let grantStatus: abilityAccessCtrl.GrantStatus = abilityAccessCtrl.GrantStatus.PERMISSION_DENIED;
60   
61     // Obtain the token ID of the application.
62     let tokenId: number = 0;
63     try {
64       let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
65       let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
66       tokenId = appInfo.accessTokenId;
67     } catch (error) {
68       const err: BusinessError = error as BusinessError;
69       console.error(`Failed to get bundle info for self. Code is ${err.code}, message is ${err.message}`);
70     }
71   
72     // Check whether the user has granted the permission.
73     try {
74       grantStatus = await atManager.checkAccessToken(tokenId, permission);
75     } catch (error) {
76       const err: BusinessError = error as BusinessError;
77       console.error(`Failed to check access token. Code is ${err.code}, message is ${err.message}`);
78     }
79   
80     return grantStatus;
81   }
82   
83   async function checkPermissions(): Promise<void> {
84     let grantStatus: abilityAccessCtrl.GrantStatus = await checkPermissionGrant(permissions[0]);
85   
86     if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
87       // If the user has granted the permission, the application can use the microphone.
88     } else {
89       // Request the permission for using the microphone.
90     }
91   }
92   ```
93
943. Request user authorization when your application needs to access the microphone.
95
96   Use [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.
97
98   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.
99
100   When applying for 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.
101
102   <!--RP1--><!--RP1End-->
103
104   <!--RP2-->
105   - Sample code for requesting user authorization using UIAbility
106
107      ```ts
108      import { abilityAccessCtrl, common, Permissions, UIAbility } from '@kit.AbilityKit';
109      import { window } from '@kit.ArkUI';
110      import { BusinessError } from '@kit.BasicServicesKit';
111      
112      const permissions: Array<Permissions> = ['ohos.permission.MICROPHONE'];
113      function reqPermissionsFromUser(permissions: Array<Permissions>, context: common.UIAbilityContext): void {
114        let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
115        // Determine whether to display a user authorization dialog box based on the return value of requestPermissionsFromUser.
116        atManager.requestPermissionsFromUser(context, permissions).then((data) => {
117          let grantStatus: Array<number> = data.authResults;
118          let length: number = grantStatus.length;
119          for (let i = 0; i < length; i++) {
120            if (grantStatus[i] === 0) {
121              // If the user grants the permission, the application can use the microphone.
122            } else {
123              // 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.
124              return;
125            }
126          }
127          // The authorization is successful.
128        }).catch((err: BusinessError) => {
129          console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);
130        })
131      }
132      export default class EntryAbility extends UIAbility {
133        onWindowStageCreate(windowStage: window.WindowStage): void {
134          // ...
135          windowStage.loadContent('pages/Index', (err, data) => {
136            reqPermissionsFromUser(permissions, this.context);
137          // ...
138          });
139        }
140      
141        // ...
142      }
143      ```
144
145   - Sample code for requesting user authorization on the UI
146
147      ```ts
148      import { abilityAccessCtrl, common, Permissions } from '@kit.AbilityKit';
149      import { BusinessError } from '@kit.BasicServicesKit';
150      
151      const permissions: Array<Permissions> = ['ohos.permission.MICROPHONE'];
152      function reqPermissionsFromUser(permissions: Array<Permissions>, context: common.UIAbilityContext): void {
153        let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
154        // Determine whether to display a user authorization dialog box based on the return value of requestPermissionsFromUser.
155        atManager.requestPermissionsFromUser(context, permissions).then((data) => {
156          let grantStatus: Array<number> = data.authResults;
157          let length: number = grantStatus.length;
158          for (let i = 0; i < length; i++) {
159            if (grantStatus[i] === 0) {
160              // If the user grants the permission, the application can use the microphone.
161            } else {
162              // 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.
163              return;
164            }
165          }
166          // The authorization is successful.
167        }).catch((err: BusinessError) => {
168          console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);
169        })
170      }
171      
172      @Entry
173      @Component
174      struct Index {
175        aboutToAppear() {
176          const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
177          reqPermissionsFromUser(permissions, context);
178        }
179      
180        build() {
181          // ...
182        }
183      }
184      ```
185   <!--RP2End-->
186
1874. Perform subsequent operations based on the authorization result.
188
189   After [requestPermissionsFromUser()](../../reference/apis-ability-kit/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) is called, the application waits for the user authorization result. If the user has granted the permission, the application can use the microphone. Otherwise, display a message indicating that user authorization is required, and direct the user to set the permission in the **Settings** page.<!--RP3-->
190
191   Path: **Settings**\> **Privacy**\> **Permission manager**\> **Apps**\> Target app<!--RP3End-->
192