• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Applying for Permissions
2
3## When to Use
4
5Application permissions are used to prevent unauthorized access to sensitive data or critical functions. The [Ability Privilege Level (APL)](accesstoken-overview.md#application-apls) of an application can be **normal** (default), **system_basic**, or **system_core**. 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
16The permissions required by an application must be declared one by one in the configuration file of the project. Otherwise, the application cannot obtain the permissions.
17
18> **NOTE**
19>
20> If an application of the **normal** APL requires a permission of the **system_basic** or **system_core** level, you must also declare the permission in the [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 required. <br>Value:<br>- **inuse**: The permission is required only when the application is in use.<br>- **always**: The permission is required no matter whether the application is in use.|
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
121User authorization is required when an application needs to access user privacy information (such as Location or Calendar information) or using system abilities (such as the camera ability to take photos or record videos). In this case, the application requires a **user_grant** permission. Before the application accesses the data or using the system ability, 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 user authorization
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 previous 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. 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, user authorization is required.
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(`Failed to get bundle info for self. 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(`Failed to check access token. 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(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);
218
219       // ...
220     }
221   }
222   ```
223
224   Sample code for requesting user authorization on the UI:
225   ```typescript
226   import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
227   import common from '@ohos.app.ability.common';
228
229   const permissions: Array<Permissions> = ['ohos.permission.READ_CALENDAR'];
230
231   @Entry
232   @Component
233   struct Index {
234     reqPermissionsFromUser(permissions: Array<Permissions>): void {
235       let context = getContext(this) as common.UIAbilityContext;
236       let atManager = abilityAccessCtrl.createAtManager();
237       // The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization.
238       atManager.requestPermissionsFromUser(context, permissions).then((data) => {
239         let grantStatus: Array<number> = data.authResults;
240         let length: number = grantStatus.length;
241         for (let i = 0; i < length; i++) {
242           if (grantStatus[i] === 0) {
243             // If the user has granted the permission, the application can access the Calendar.
244           } else {
245             // 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.
246             return;
247           }
248         }
249         // The authorization is successful.
250       }).catch((err) => {
251         console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);
252       })
253     }
254
255     // Page display.
256     build() {
257       // ...
258     }
259   }
260   ```
261
2624. Perform subsequent operations based on the authorization result.
263
264   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.
265
266   ```ts
267   function openPermissionsInSystemSettings(): void {
268     let context = getContext(this) as common.UIAbilityContext;
269     let wantInfo = {
270       action: 'action.settings.app.info',
271       parameters: {
272         settingsParamBundleName: 'com.example.myapplication' // Open the Details page of the application.
273       }
274     }
275     context.startAbility(wantInfo).then(() => {
276       // ...
277     }).catch((err) => {
278       // ...
279     })
280   }
281   ```
282
283### FA Model
284
285Call [requestPermissionsFromUser()](../reference/apis/js-apis-inner-app-context.md#contextrequestpermissionsfromuser7) to request user authorization.
286
287```js
288import featureAbility from '@ohos.ability.featureAbility';
289
290reqPermissions() {
291    let context = featureAbility.getContext();
292    let array:Array<string> = ["ohos.permission.PERMISSION2"];
293    // The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization.
294    context.requestPermissionsFromUser(array, 1).then(function(data) {
295        console.log("data:" + JSON.stringify(data));
296        console.log("data permissions:" + JSON.stringify(data.permissions));
297        console.log("data result:" + JSON.stringify(data.authResults));
298    }, (err) => {
299        console.error('Failed to start ability', err.code);
300    });
301}
302```
303## Pre-authorizing user_grant Permissions
304By default, the **user_grant** permissions must be dynamically authorized by the user through a dialog box. However, some pre-installed applications may require **user_grant** permissions, for example, the system camera application requires the **ohos.permission.MICROPHONE** permission. In this case, you can pre-authorize **user_grant** permissions for pre-installed applications 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.
305
306The **install_list_permissions.json** file contains the following fields:
307
308- **bundleName**: bundle name of the application.
309- **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).
310- **permissions**: The **name** field specifies the name of the **user_grant** permission to pre-authorize. The **userCancellable** field 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.
311
312> **NOTE**
313>
314> The **install_list_permissions.json** file is available only for preinstalled applications.
315
316```json
317[
318  // ...
319  {
320    "bundleName": "com.example.myapplication", // Bundle Name.
321    "app_signature": ["****"], // Fingerprint information.
322    "permissions":[
323      {
324        "name": "ohos.permission.PERMISSION_X", // Permission to pre-authorize.
325        "userCancellable": false // The user cannot revoke the authorization.
326      },
327      {
328        "name": "ohos.permission.PERMISSION_X", // Permission to pre-authorize.
329        "userCancellable": true // The user can revoke the authorization.
330      }
331    ]
332  }
333]
334```
335