• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Applying for Permissions
2
3## When to Use
4
5The [Ability Privilege Level (APL)](accesstoken-overview.md#application-apls) of an application can be **normal**, **system_basic**, or **system_core**. The default APL is **normal**. The [permission types](accesstoken-overview.md#permission-types) include **system_grant** and **user_grant**. For details about the permissions for applications, see the [Application Permission List](permission-list.md).
6
7This document describes the following operations:
8
9- [Declaring Permissions in the Configuration File](#declaring-permissions-in-the-configuration-file)
10- [Declaring the ACL](#declaring-the-acl)
11- [Requesting User Authorization](#requesting-user-authorization)
12- [Pre-Authorizing user_grant Permissions](#pre-authorizing-user_grant-permissions)
13
14## Declaring Permissions in the Configuration File
15
16During the development, you need to declare the permissions required by your application one by one in the project configuration file. The application cannot obtain the permissions that are not declared in the configuration file. OpenHarmony provides two application models: FA model and stage model. For more information, see [Application Models](../application-models/application-model-description.md). The application bundle and configuration file vary with the application model.
17
18> **NOTE**
19>
20> The default APL of an application is **normal**. When an application of the **normal** APL needs a permission of the **system_basic** or **system_core** level, you must declare the permission in the configuration file and the [Access Control List (ACL)](#declaring-the-acl).
21
22The following table describes the fields in the configuration file.
23
24| Field     | Mandatory| Description                                                        |
25| --------- | -------- | ------------------------------------------------------------ |
26| name      | Yes      | Name of the permission.                                                  |
27| reason    | No      | Reason for requesting the permission.<br>This parameter is mandatory when a user_grant permission is required.|
28| usedScene | No      | Application scenario of the permission.<br>This parameter is mandatory when a user_grant permission is required.|
29| abilities | No      | Abilities that require the permission. The value is an array.<br>**Applicable model**: stage|
30| ability   | No      | Abilities that require the permission. The value is an array.<br>**Applicable model**: FA|
31| when      | No      | Time when the permission is used. <br>Value:<br>- **inuse**: The permission applies only to a foreground application.<br>- **always**: The permission applies to both the foreground and background applications.|
32
33### Stage Model
34
35If your application is developed based on the stage model, declare the required permissions in [**module.json5**](../quick-start/module-configuration-file.md).
36
37```json
38{
39  "module" : {
40    // ...
41    "requestPermissions":[
42      {
43        "name" : "ohos.permission.PERMISSION1",
44        "reason": "$string:reason",
45        "usedScene": {
46          "abilities": [
47            "FormAbility"
48          ],
49          "when":"inuse"
50        }
51      },
52      {
53        "name" : "ohos.permission.PERMISSION2",
54        "reason": "$string:reason",
55        "usedScene": {
56          "abilities": [
57            "FormAbility"
58          ],
59          "when":"always"
60        }
61      }
62    ]
63  }
64}
65```
66
67### FA Model
68
69If your application is developed based on the FA model, declare the required permissions in **config.json**.
70
71```json
72{
73  "module" : {
74    // ...
75    "reqPermissions":[
76      {
77        "name" : "ohos.permission.PERMISSION1",
78        "reason": "$string:reason",
79        "usedScene": {
80          "ability": [
81            "FormAbility"
82          ],
83          "when":"inuse"
84        }
85      },
86      {
87        "name" : "ohos.permission.PERMISSION2",
88        "reason": "$string:reason",
89        "usedScene": {
90          "ability": [
91            "FormAbility"
92          ],
93          "when":"always"
94        }
95      }
96    ]
97  }
98}
99```
100
101## Declaring the ACL
102
103If an application of the **normal** APL requires permissions of the **system_basic** or **system_core** level, you must also declare the required permissions in the ACL.
104
105For example, if an application needs to access audio clips of a user and capture screenshots, it requires the **ohos.permission.WRITE_AUDIO** permission (of the **system_basic** level) and the **ohos.permission.CAPTURE_SCREEN** permission (of the **system_core** level). In this case, you need to add the required permissions to the **acls** field in the [HarmonyAppProvision configuration file](app-provision-structure.md).
106
107```json
108{
109	// ...
110	"acls":{
111		"allowed-acls":[
112			"ohos.permission.WRITE_AUDIO",
113            "ohos.permission.CAPTURE_SCREEN"
114		]
115	}
116}
117```
118
119## Requesting User Authorization
120
121The permissions for accessing user privacy information or using system abilities (for example, accessing Location or Calendar information or using the camera to take photos or record videos) request user authorization. Before an application that requires a **user_grant** permission is called, a verification is performed to check whether the user has granted the permission to the application. If the user has not granted the permission, a dialog box will be displayed to request user authorization. The following figure shows an example.
122
123**Figure 1** Requesting authorization from a user
124![](figures/permission-read_calendar.png)
125
126> **NOTE**
127>
128> Each time before an API protected by a **user_grant** permission is called, **requestPermissionsFromUser()** will be called to request user authorization. After the permission is granted, the user may revoke the authorization in **Settings**. Therefore, the previously granted authorization status cannot be persistent.
129
130### Stage Model
131
132Example: Apply for the permission for an application to access the Calendar.
133
1341. Declare the **ohos.permission.READ_CALENDAR** permission in the configuration file.<br>For details, see [Declaring Permissions in the Configuration File](#declaring-permissions-in-the-configuration-file).
135
1362. Check whether the user has granted the permission.
137
138   Use [checkAccessToken()](../reference/apis/js-apis-abilityAccessCtrl.md#checkaccesstoken9) to check whether the user has granted the permission. If yes, the application can access the Calendar. Otherwise, request authorization from the user.
139
140   ```ts
141   import bundleManager from '@ohos.bundle.bundleManager';
142   import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
143
144   async function checkAccessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
145     let atManager = abilityAccessCtrl.createAtManager();
146     let grantStatus: abilityAccessCtrl.GrantStatus;
147
148     // Obtain the access token ID of the application.
149     let tokenId: number;
150     try {
151       let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
152       let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
153       tokenId = appInfo.accessTokenId;
154     } catch (err) {
155       console.error(`getBundleInfoForSelf failed, code is ${err.code}, message is ${err.message}`);
156     }
157
158     // Check whether the user has granted the permission.
159     try {
160       grantStatus = await atManager.checkAccessToken(tokenId, permission);
161     } catch (err) {
162       console.error(`checkAccessToken failed, code is ${err.code}, message is ${err.message}`);
163     }
164
165     return grantStatus;
166   }
167
168   async function checkPermissions(): Promise<void> {
169     const permissions: Array<Permissions> = ['ohos.permission.READ_CALENDAR'];
170     let grantStatus: abilityAccessCtrl.GrantStatus = await checkAccessToken(permissions[0]);
171
172     if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
173       // If the user has granted the permission, the application can access the Calendar.
174     } else {
175       // Apply for the permission to access the Calendar.
176     }
177   }
178   ```
179
1803. Request user authorization dynamically.
181
182   Use [requestPermissionsFromUser()](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) to apply for permissions from the user when the application is running. A list of permissions, such as the permissions to access the Location, Calendar, camera, and microphone, can be passed in. The user can grant or deny the permissions.
183
184   You can have [**requestPermissionsFromUser()**](../reference/apis/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.
185
186   Sample code for requesting user authorization using UIAbility:
187
188   ```typescript
189   import UIAbility from '@ohos.app.ability.UIAbility';
190   import window from '@ohos.window';
191   import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
192
193   const permissions: Array<Permissions> = ['ohos.permission.READ_CALENDAR'];
194
195   export default class EntryAbility extends UIAbility {
196     // ...
197
198     onWindowStageCreate(windowStage: window.WindowStage) {
199       // Main window is created. Set the main page for this ability.
200       let context = this.context;
201       let atManager = abilityAccessCtrl.createAtManager();
202       // The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization.
203
204       atManager.requestPermissionsFromUser(context, permissions).then((data) => {
205         let grantStatus: Array<number> = data.authResults;
206         let length: number = grantStatus.length;
207         for (let i = 0; i < length; i++) {
208           if (grantStatus[i] === 0) {
209             // If the user has granted the permission, the application can access the Calendar.
210           } else {
211             // If the user has not granted the permission, display a message indicating that user authorization is required, and direct the user to the Settings page to set the permission.
212             return;
213           }
214         }
215         // The authorization is successful.
216       }).catch((err) => {
217         console.error(`requestPermissionsFromUser failed, code is ${err.code}, message is ${err.message}`);
218       })
219
220       // ...
221     }
222   }
223   ```
224
225   Sample code for requesting user authorization on the UI:
226   ```typescript
227   import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
228   import common from '@ohos.app.ability.common';
229
230   const permissions: Array<Permissions> = ['ohos.permission.READ_CALENDAR'];
231
232   @Entry
233   @Component
234   struct Index {
235     reqPermissionsFromUser(permissions: Array<Permissions>): void {
236       let context = getContext(this) as common.UIAbilityContext;
237       let atManager = abilityAccessCtrl.createAtManager();
238       // The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization.
239       atManager.requestPermissionsFromUser(context, permissions).then((data) => {
240         let grantStatus: Array<number> = data.authResults;
241         let length: number = grantStatus.length;
242         for (let i = 0; i < length; i++) {
243           if (grantStatus[i] === 0) {
244             // If the user has granted the permission, the application can access the Calendar.
245           } else {
246             // If the user has not granted the permission, display a message indicating that user authorization is required, and direct the user to the Settings page to set the permission.
247             return;
248           }
249         }
250         // The authorization is successful.
251       }).catch((err) => {
252         console.error(`requestPermissionsFromUser failed, code is ${err.code}, message is ${err.message}`);
253       })
254     }
255
256     // Page display.
257     build() {
258       // ...
259     }
260   }
261   ```
262
2634. Perform subsequent operations based on the authorization result.
264
265   After [requestPermissionsFromUser()](../reference/apis/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 access the Calendar. If the user has not granted the permission, a message will be displayed indicating that user authorization is required, and the user is directed to **Settings** to set the permission.
266
267   ```ts
268   function openPermissionsInSystemSettings(): void {
269     let context = getContext(this) as common.UIAbilityContext;
270     let wantInfo = {
271       action: 'action.settings.app.info',
272       parameters: {
273         settingsParamBundleName: 'com.example.myapplication' // Open the Details page of the application.
274       }
275     }
276     context.startAbility(wantInfo).then(() => {
277       // ...
278     }).catch((err) => {
279       // ...
280     })
281   }
282   ```
283
284### FA Model
285
286Call [requestPermissionsFromUser()](../reference/apis/js-apis-inner-app-context.md#contextrequestpermissionsfromuser7) to request user authorization.
287
288```js
289import featureAbility from '@ohos.ability.featureAbility';
290
291reqPermissions() {
292    let context = featureAbility.getContext();
293    let array:Array<string> = ["ohos.permission.PERMISSION2"];
294    // The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization.
295    context.requestPermissionsFromUser(array, 1).then(function(data) {
296        console.log("data:" + JSON.stringify(data));
297        console.log("data permissions:" + JSON.stringify(data.permissions));
298        console.log("data result:" + JSON.stringify(data.authResults));
299    }, (err) => {
300        console.error('Failed to start ability', err.code);
301    });
302}
303```
304## Pre-Authorizing user_grant Permissions
305By default, the **user_grant** permissions must be dynamically authorized by the user through a dialog box. However, if you do not want the user authorization dialog box to display for pre-installed applications, you can pre-authorize the permissions, for example, the **ohos.permission.MICROPHONE** permission, in the [**install_list_permission.json**](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list_permissions.json) file. The **install_list_permissions.json** file is in the **/system/etc/app/** directory on a device, and is loaded when the device starts. When the application is installed, the **user_grant** permissions in the file are granted.<br> The **install_list_permissions.json** file contains the following fields:
306
307- **bundleName**: bundle name of the application.
308- **app_signature**: fingerprint information of the application. For details, see **Configuration in install_list_capability.json** in the [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md).
309- **permissions**: **name** specifies the name of the **user_grant** permission to pre-authorize. **userCancellable** specifies whether the user can revoke the pre-authorization. The value **true** means the user can revoke the pre-authorization; the value **false** means the opposite.
310
311> **NOTE**<br>This file is available only for preinstalled applications.
312
313```json
314[
315  // ...
316  {
317    "bundleName": "com.example.myapplication", // Bundle Name.
318    "app_signature": ["****"], // Fingerprint information.
319    "permissions":[
320      {
321        "name": "ohos.permission.PERMISSION_X", // Permission to pre-authorize.
322        "userCancellable": false // The user cannot revoke the authorization.
323      },
324      {
325        "name": "ohos.permission.PERMISSION_X", // Permission to pre-authorize.
326        "userCancellable": true // The user can revoke the authorization.
327      }
328    ]
329  }
330]
331```
332