accesstoken-guidelines.md 12.1 KB
Newer Older
A
Annie_wang 已提交
1
# Permission Application Guide
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
During 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.
A
annie_wangli 已提交
17

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

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

A
Annie_wang 已提交
22 23 24
| Field     | Mandatory| Description                                                        |
| --------- | -------- | ------------------------------------------------------------ |
| name      | Yes      | Name of the permission.                                                  |
A
Annie_wang 已提交
25 26
| reason    | No      | Reason for requesting the permission.<br>This field is mandatory when a user_grant permission is required.|
| usedScene | No      | Application scenario of the permission.<br>This field is mandatory when a user_grant permission is required.|
A
Annie_wang 已提交
27 28 29
| 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 已提交
30

A
Annie_wang 已提交
31
### Stage Model
A
Annie_wang 已提交
32

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

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

A
Annie_wang 已提交
65
### FA Model
A
Annie_wang 已提交
66

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

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

A
Annie_wang 已提交
99
## Declaring the ACL
A
annie_wangli 已提交
100

A
Annie_wang 已提交
101
If an application of the **normal** APL requires permissions of the **system_basic** or **system_core** level, you need to declare the required permissions in the ACL.
A
Annie_wang 已提交
102

A
Annie_wang 已提交
103
For example, if an application needs to access audio files 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 已提交
104

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

A
Annie_wang 已提交
117
## Requesting User Authorization
A
annie_wangli 已提交
118

A
Annie_wang 已提交
119
If an application needs to access user privacy information or use system abilities, for example, accessing location or calendar information or using the camera to take photos or record videos, it must request the permission from the user. A permission verification is performed first to determine whether the current caller has the corresponding permission. If the application has not obtained that permission, a dialog box will be displayed to request user authorization. The following figure shows an example.
120 121

![](figures/permission-read_calendar.png)
A
annie_wangli 已提交
122

A
Annie_wang 已提交
123
> **NOTE**<br>Each time before an API protected by a user_grant permission is accessed, [**requestPermissionsFromUser()**](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) will be called to request user authorization. After the permission is dynamically granted, the user may revoke the authorization. Therefore, the previously granted authorization status cannot be persistent.
A
annie_wangli 已提交
124

A
Annie_wang 已提交
125
### Stage Model
A
annie_wangli 已提交
126

A
Annie_wang 已提交
127
Example: Request the permission for an application to access calendar information.
A
Annie_wang 已提交
128 129 130

1. Apply for the **ohos.permission.READ_CALENDAR** permission. For details, see [Declaring Permissions in the Configuration File](#declaring-permissions-in-the-configuration-file).

A
Annie_wang 已提交
131
2. Call [**requestPermissionsFromUser()**](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) in the **onWindowStageCreate()** callback of the UIAbility to dynamically apply for the permission, or request user authorization on the UI based on service requirements. The return value of [requestPermissionsFromUser()](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) indicates whether the application has the permission. If yes, the target API can be called.
A
Annie_wang 已提交
132
   
A
Annie_wang 已提交
133 134 135 136
   Request user authorization in UIAbility.
   
   ```typescript
   import UIAbility from '@ohos.app.ability.UIAbility';
A
Annie_wang 已提交
137
   import window from '@ohos.window';
A
Annie_wang 已提交
138
   import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
A
Annie_wang 已提交
139 140 141 142
   
   export default class EntryAbility extends UIAbility {
       // ...
   
A
Annie_wang 已提交
143
       onWindowStageCreate(windowStage: window.WindowStage) {
A
Annie_wang 已提交
144 145
           // Main window is created, set main page for this ability
           let context = this.context;
A
Annie_wang 已提交
146
           let atManager = abilityAccessCtrl.createAtManager();
A
Annie_wang 已提交
147 148
           // The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization.
           const permissions: Array<Permissions> = ['ohos.permission.READ_CALENDAR'];
A
Annie_wang 已提交
149
           atManager.requestPermissionsFromUser(context, permissions).then((data) => {
A
Annie_wang 已提交
150 151
               console.info(`[requestPermissions] data: ${JSON.stringify(data)}`);
               let grantStatus: Array<number> = data.authResults;
A
Annie_wang 已提交
152 153 154 155 156 157
               let length: number = grantStatus.length;
               for (let i = 0; i < length; i++) {
                   if (grantStatus[i] !== 0) {
                       // The authorization fails.
                       return;
                   }
A
Annie_wang 已提交
158
               }
A
Annie_wang 已提交
159
               // The authorization is successful.
A
Annie_wang 已提交
160 161 162 163 164 165 166 167 168 169 170
           }).catch((err) => {
               console.error(`[requestPermissions] Failed to start request permissions. Error: ${JSON.stringify(err)}`);
           })
           
           // ...
       }
   }
   ```
   
   Request user authorization on the UI.
   ```typescript
A
Annie_wang 已提交
171
   import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
A
Annie_wang 已提交
172 173 174 175 176 177 178
   import common from '@ohos.app.ability.common';
   
   @Entry
   @Component
   struct Index {
     reqPermissions() {
       let context = getContext(this) as common.UIAbilityContext;
A
Annie_wang 已提交
179
       let atManager = abilityAccessCtrl.createAtManager();
A
Annie_wang 已提交
180 181
       // The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization.
       const permissions: Array<Permissions> = ['ohos.permission.READ_CALENDAR'];
A
Annie_wang 已提交
182
       atManager.requestPermissionsFromUser(context, permissions).then((data) => {
A
Annie_wang 已提交
183 184
         console.info(`[requestPermissions] data: ${JSON.stringify(data)}`);
         let grantStatus: Array<number> = data.authResults;
A
Annie_wang 已提交
185 186 187 188 189 190
         let length: number = grantStatus.length;
         for (let i = 0; i < length; i++) {
           if (grantStatus[i] !== 0) {
             // The authorization fails.
             return;
           }
A
Annie_wang 已提交
191
         }
A
Annie_wang 已提交
192
         // The authorization is successful.
A
Annie_wang 已提交
193 194 195 196 197 198 199 200 201 202 203
       }).catch((err) => {
         console.error(`[requestPermissions] Failed to start request permissions. Error: ${JSON.stringify(err)}`);
       })
     }
   
     // Page display.
     build() {
       // ...
     }
   }
   ```
A
annie_wangli 已提交
204

A
Annie_wang 已提交
205
### FA Model
A
annie_wangli 已提交
206

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

```js
A
Annie_wang 已提交
210 211 212 213
import featureAbility from '@ohos.ability.featureAbility';

reqPermissions() {
    let context = featureAbility.getContext();
A
Annie_wang 已提交
214
    let array:Array<string> = ["ohos.permission.PERMISSION2"];
A
Annie_wang 已提交
215
    // The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization.
A
Annie_wang 已提交
216
    context.requestPermissionsFromUser(array, 1).then(function(data) {
A
Annie_wang 已提交
217 218 219
        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 已提交
220
    }, (err) => {
A
Annie_wang 已提交
221
        console.error('Failed to start ability', err.code);
A
Annie_wang 已提交
222
    });
A
Annie_wang 已提交
223 224 225
}
```
## Pre-Authorizing user_grant Permissions
A
Annie_wang 已提交
226
By default, the **user_grant** permissions must be dynamically authorized by the user through a dialog box. However, for pre-installed applications, you can pre-authorize the permissions, for example, the **ohos.permission.MICROPHONE** permission for camera applications, in the [**install_list_permission.json**](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list_permissions.json) file to prevent the user authorization dialog box from being displayed. The **install_list_permissions.json** file is in the **/system/etc/app/** directory on a device. When the device is started, the **install_list_permissions.json** file is loaded. When the application is installed, the user_grant permissions in the file are granted. The **install_list_permissions.json** file contains the following fields:
A
annie_wangli 已提交
227

A
Annie_wang 已提交
228
- **bundleName**: bundle name of the application.
A
Annie_wang 已提交
229 230
- **app_signature**: fingerprint information of the application. For details, see **Configuration in install_list_capability.json** in [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md).
- **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 已提交
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251

> **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 已提交
252
```