accesstoken-guidelines.md 15.0 KB
Newer Older
A
Annie_wang 已提交
1
# Applying for Permissions
A
annie_wangli 已提交
2

A
Annie_wang 已提交
3
## When to Use
A
annie_wangli 已提交
4

A
Annie_wang 已提交
5
The [Ability Privilege Level (APL)](accesstoken-overview.md#app-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).
A
annie_wangli 已提交
6

A
Annie_wang 已提交
7
This document describes the following operations:
A
annie_wangli 已提交
8

A
Annie_wang 已提交
9
- [Declaring Permissions in the Configuration File](#declaring-permissions-in-the-configuration-file)
A
Annie_wang 已提交
10
- [Declaring the ACL](#declaring-the-acl)
A
Annie_wang 已提交
11 12
- [Requesting User Authorization](#requesting-user-authorization)
- [Pre-Authorizing user_grant Permissions](#pre-authorizing-user_grant-permissions)
A
Annie_wang 已提交
13

A
Annie_wang 已提交
14
## Declaring Permissions in the Configuration File
A
annie_wangli 已提交
15

A
Annie_wang 已提交
16
The 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.
A
annie_wangli 已提交
17

A
Annie_wang 已提交
18 19 20
> **NOTE**
>
> 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).
A
annie_wangli 已提交
21

A
Annie_wang 已提交
22
The following table describes the fields in the configuration file.
A
annie_wangli 已提交
23

A
Annie_wang 已提交
24 25 26
| Field     | Mandatory| Description                                                        |
| --------- | -------- | ------------------------------------------------------------ |
| name      | Yes      | Name of the permission.                                                  |
A
Annie_wang 已提交
27 28
| reason    | No      | Reason for requesting the permission.<br>This parameter is mandatory when a user_grant permission is required.|
| usedScene | No      | Application scenario of the permission.<br>This parameter is mandatory when a user_grant permission is required.|
A
Annie_wang 已提交
29 30 31
| abilities | No      | Abilities that require the permission. The value is an array.<br>**Applicable model**: stage|
| ability   | No      | Abilities that require the permission. The value is an array.<br>**Applicable model**: FA|
| 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.|
A
annie_wangli 已提交
32

A
Annie_wang 已提交
33
### Stage Model
A
Annie_wang 已提交
34

A
Annie_wang 已提交
35
If your application is developed based on the stage model, declare the required permissions in [**module.json5**](../quick-start/module-configuration-file.md).
A
annie_wangli 已提交
36

A
Annie_wang 已提交
37 38
```json
{
A
Annie_wang 已提交
39
  "module" : {
A
Annie_wang 已提交
40 41
    // ...
    "requestPermissions":[
A
Annie_wang 已提交
42 43 44 45
      {
        "name" : "ohos.permission.PERMISSION1",
        "reason": "$string:reason",
        "usedScene": {
A
Annie_wang 已提交
46
          "abilities": [
A
Annie_wang 已提交
47 48 49 50 51 52 53 54 55
            "FormAbility"
          ],
          "when":"inuse"
        }
      },
      {
        "name" : "ohos.permission.PERMISSION2",
        "reason": "$string:reason",
        "usedScene": {
A
Annie_wang 已提交
56
          "abilities": [
A
Annie_wang 已提交
57 58 59 60 61 62 63
            "FormAbility"
          ],
          "when":"always"
        }
      }
    ]
  }
A
Annie_wang 已提交
64 65 66
}
```

A
Annie_wang 已提交
67
### FA Model
A
Annie_wang 已提交
68

A
Annie_wang 已提交
69
If your application is developed based on the FA model, declare the required permissions in **config.json**.
A
Annie_wang 已提交
70

A
annie_wangli 已提交
71 72
```json
{
A
Annie_wang 已提交
73
  "module" : {
A
Annie_wang 已提交
74 75
    // ...
    "reqPermissions":[
A
Annie_wang 已提交
76 77 78 79
      {
        "name" : "ohos.permission.PERMISSION1",
        "reason": "$string:reason",
        "usedScene": {
A
Annie_wang 已提交
80
          "ability": [
A
Annie_wang 已提交
81 82 83
            "FormAbility"
          ],
          "when":"inuse"
A
Annie_wang 已提交
84 85 86 87 88 89
        }
      },
      {
        "name" : "ohos.permission.PERMISSION2",
        "reason": "$string:reason",
        "usedScene": {
A
Annie_wang 已提交
90
          "ability": [
A
Annie_wang 已提交
91 92
            "FormAbility"
          ],
A
Annie_wang 已提交
93
          "when":"always"
A
Annie_wang 已提交
94 95 96 97
        }
      }
    ]
  }
A
annie_wangli 已提交
98 99
}
```
A
Annie_wang 已提交
100

A
Annie_wang 已提交
101
## Declaring the ACL
A
annie_wangli 已提交
102

A
Annie_wang 已提交
103
If 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.
A
Annie_wang 已提交
104

A
Annie_wang 已提交
105
For 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).
A
Annie_wang 已提交
106

A
annie_wangli 已提交
107 108
```json
{
A
Annie_wang 已提交
109 110 111 112 113 114 115
	// ...
	"acls":{
		"allowed-acls":[
			"ohos.permission.WRITE_AUDIO",
            "ohos.permission.CAPTURE_SCREEN"
		]
	}
A
annie_wangli 已提交
116 117 118
}
```

A
Annie_wang 已提交
119
## Requesting User Authorization
A
annie_wangli 已提交
120

A
Annie_wang 已提交
121
The 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

A
Annie_wang 已提交
123
**Figure 1** Requesting authorization from a user  
124
![](figures/permission-read_calendar.png)
A
annie_wangli 已提交
125

A
Annie_wang 已提交
126 127 128
> **NOTE**
>
> 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.
A
annie_wangli 已提交
129

A
Annie_wang 已提交
130
### Stage Model
A
annie_wangli 已提交
131

A
Annie_wang 已提交
132
Example: Apply for the permission for an application to access the Calendar.
A
Annie_wang 已提交
133

A
Annie_wang 已提交
134
1. 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).
A
Annie_wang 已提交
135

A
Annie_wang 已提交
136 137 138 139 140 141 142 143 144 145 146
2. Check whether the user has granted the permission.

   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.

   ```ts
   import bundleManager from '@ohos.bundle.bundleManager';
   import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
   
   async function checkAccessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
     let atManager = abilityAccessCtrl.createAtManager();
     let grantStatus: abilityAccessCtrl.GrantStatus;
A
Annie_wang 已提交
147
   
A
Annie_wang 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
     // Obtain the access token ID of the application.
     let tokenId: number;
     try {
       let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
       let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
       tokenId = appInfo.accessTokenId;
     } catch (err) {
       console.error(`getBundleInfoForSelf failed, code is ${err.code}, message is ${err.message}`);
     }
   
     // Check whether the user has granted the permission.
     try {
       grantStatus = await atManager.checkAccessToken(tokenId, permission);
     } catch (err) {
       console.error(`checkAccessToken failed, code is ${err.code}, message is ${err.message}`);
     }
A
Annie_wang 已提交
164
   
A
Annie_wang 已提交
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
     return grantStatus;
   }
   
   async function checkPermissions(): Promise<void> {
     const permissions: Array<Permissions> = ['ohos.permission.READ_CALENDAR'];
     let grantStatus: abilityAccessCtrl.GrantStatus = await checkAccessToken(permissions[0]);
   
     if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
       // If the user has granted the permission, the application can access the Calendar.
     } else {
       // Apply for the permission to access the Calendar.
     }
   }
   ```

3. Request user authorization dynamically.

   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.

   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.

   Sample code for requesting user authorization using UIAbility:

A
Annie_wang 已提交
188 189
   ```typescript
   import UIAbility from '@ohos.app.ability.UIAbility';
A
Annie_wang 已提交
190
   import window from '@ohos.window';
A
Annie_wang 已提交
191
   import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
A
Annie_wang 已提交
192
   
A
Annie_wang 已提交
193 194
   const permissions: Array<Permissions> = ['ohos.permission.READ_CALENDAR'];
   
A
Annie_wang 已提交
195
   export default class EntryAbility extends UIAbility {
A
Annie_wang 已提交
196
     // ...
A
Annie_wang 已提交
197
   
A
Annie_wang 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
     onWindowStageCreate(windowStage: window.WindowStage) {
       // Main window is created. Set the main page for this ability.
       let context = this.context;
       let atManager = abilityAccessCtrl.createAtManager();
       // The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization.
   
       atManager.requestPermissionsFromUser(context, permissions).then((data) => {
         let grantStatus: Array<number> = data.authResults;
         let length: number = grantStatus.length;
         for (let i = 0; i < length; i++) {
           if (grantStatus[i] === 0) {
             // If the user has granted the permission, the application can access the Calendar.
           } else {
             // 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.
             return;
           }
         }
         // The authorization is successful.
       }).catch((err) => {
         console.error(`requestPermissionsFromUser failed, code is ${err.code}, message is ${err.message}`);
       })
   
       // ...
     }
A
Annie_wang 已提交
222 223
   }
   ```
A
Annie_wang 已提交
224 225

   Sample code for requesting user authorization on the UI:
A
Annie_wang 已提交
226
   ```typescript
A
Annie_wang 已提交
227
   import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
A
Annie_wang 已提交
228 229
   import common from '@ohos.app.ability.common';
   
A
Annie_wang 已提交
230 231
   const permissions: Array<Permissions> = ['ohos.permission.READ_CALENDAR'];
   
A
Annie_wang 已提交
232 233 234
   @Entry
   @Component
   struct Index {
A
Annie_wang 已提交
235
     reqPermissionsFromUser(permissions: Array<Permissions>): void {
A
Annie_wang 已提交
236
       let context = getContext(this) as common.UIAbilityContext;
A
Annie_wang 已提交
237
       let atManager = abilityAccessCtrl.createAtManager();
A
Annie_wang 已提交
238
       // The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization.
A
Annie_wang 已提交
239
       atManager.requestPermissionsFromUser(context, permissions).then((data) => {
A
Annie_wang 已提交
240
         let grantStatus: Array<number> = data.authResults;
A
Annie_wang 已提交
241 242
         let length: number = grantStatus.length;
         for (let i = 0; i < length; i++) {
A
Annie_wang 已提交
243 244 245 246
           if (grantStatus[i] === 0) {
             // If the user has granted the permission, the application can access the Calendar.
           } else {
             // 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.
A
Annie_wang 已提交
247 248
             return;
           }
A
Annie_wang 已提交
249
         }
A
Annie_wang 已提交
250
         // The authorization is successful.
A
Annie_wang 已提交
251
       }).catch((err) => {
A
Annie_wang 已提交
252
         console.error(`requestPermissionsFromUser failed, code is ${err.code}, message is ${err.message}`);
A
Annie_wang 已提交
253 254 255 256 257 258 259 260 261
       })
     }
   
     // Page display.
     build() {
       // ...
     }
   }
   ```
A
annie_wangli 已提交
262

A
Annie_wang 已提交
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
4. Perform subsequent operations based on the authorization result.

   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.

   ```ts
   function openPermissionsInSystemSettings(): void {
     let context = getContext(this) as common.UIAbilityContext;
     let wantInfo = {
       action: 'action.settings.app.info',
       parameters: {
         settingsParamBundleName: 'com.example.myapplication' // Open the Details page of the application.
       }
     }
     context.startAbility(wantInfo).then(() => {
       // ...
     }).catch((err) => {
       // ...
     })
   }
   ```

A
Annie_wang 已提交
284
### FA Model
A
annie_wangli 已提交
285

A
Annie_wang 已提交
286
Call [requestPermissionsFromUser()](../reference/apis/js-apis-inner-app-context.md#contextrequestpermissionsfromuser7) to request user authorization.
A
annie_wangli 已提交
287 288

```js
A
Annie_wang 已提交
289 290 291 292
import featureAbility from '@ohos.ability.featureAbility';

reqPermissions() {
    let context = featureAbility.getContext();
A
Annie_wang 已提交
293
    let array:Array<string> = ["ohos.permission.PERMISSION2"];
A
Annie_wang 已提交
294
    // The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization.
A
Annie_wang 已提交
295
    context.requestPermissionsFromUser(array, 1).then(function(data) {
A
Annie_wang 已提交
296 297 298
        console.log("data:" + JSON.stringify(data));
        console.log("data permissions:" + JSON.stringify(data.permissions));
        console.log("data result:" + JSON.stringify(data.authResults));
A
Annie_wang 已提交
299
    }, (err) => {
A
Annie_wang 已提交
300
        console.error('Failed to start ability', err.code);
A
Annie_wang 已提交
301
    });
A
Annie_wang 已提交
302 303 304
}
```
## Pre-Authorizing user_grant Permissions
A
Annie_wang 已提交
305
By 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:
A
annie_wangli 已提交
306

A
Annie_wang 已提交
307
- **bundleName**: bundle name of the application.
A
Annie_wang 已提交
308
- **app_signature**: fingerprint information of the application. For details, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md#configuration-in-install_list_capabilityjson).
A
Annie_wang 已提交
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.
A
Annie_wang 已提交
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330

> **NOTE**<br>This file is available only for preinstalled applications.

```json
[
  // ...
  {
    "bundleName": "com.example.myapplication", // Bundle Name.
    "app_signature": ["****"], // Fingerprint information.
    "permissions":[
      {
        "name": "ohos.permission.PERMISSION_X", // Permission to pre-authorize.
        "userCancellable": false // The user cannot revoke the authorization.
      },
      {
        "name": "ohos.permission.PERMISSION_X", // Permission to pre-authorize.
        "userCancellable": true // The user can revoke the authorization.
      }
    ]
  }
]
A
annie_wangli 已提交
331
```