accesstoken-guidelines.md 11.6 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 apps, see the [App 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 10 11 12
- [Declaring Permissions in the Configuration File](#declaring-permissions-in-the-configuration-file)
- [Declaring Permissions in the ACL](#declaring-permissions-in-the-acl)
- [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. 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 needs the **system_basic** or **system_core** APL, you must declare the permission in the configuration file and the [Access Control List (ACL)](#declaring-permissions-in-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 25 26 27 28 29
| Field     | Mandatory| Description                                                        |
| --------- | -------- | ------------------------------------------------------------ |
| name      | Yes      | Name of the permission.                                                  |
| reason    | No      | Reason for requesting the permission.<br>This field is mandatory when the requested permission needs user authorization (user_grant).|
| usedScene | No      | Application scenario of the permission.<br>This field is mandatory when the requested permission needs user authorization (user_grant).|
| 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 the application is based on the stage model, declare the 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 the 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 Permissions in the ACL
A
annie_wangli 已提交
100

A
Annie_wang 已提交
101
If an application of the **normal** level requires permissions corresponding to 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 related permissions to the **acl** 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 120
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 users. A permission verification is performed first to determine whether the current invoker 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.
<img src="figures/permission-read_calendar.png" width="40%;" />
A
annie_wangli 已提交
121

A
Annie_wang 已提交
122
> **NOTE**<br>Each time before an API protected by a permission is accessed, the **requestPermissionsFromUser()** API will be called to request user authorization. After a permission is dynamically granted, the user may revoke the permission. Therefore, the previously granted authorization status cannot be persistent.
A
annie_wangli 已提交
123

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

A
Annie_wang 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
Example: Request the permission to read calendar information for an app.

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

2. Call **requestPermissionsFromUser()** 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()** indicates whether the application has the target permission. If yes, the target API can be called normally.
  
   Request user authorization in UIAbility.
   
   ```typescript
   import UIAbility from '@ohos.app.ability.UIAbility';
   import Window from '@ohos.window';
   import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
   import { Permissions } from '@ohos.abilityAccessCtrl';
   
   export default class EntryAbility extends UIAbility {
       // ...
   
       onWindowStageCreate(windowStage: Window.WindowStage) {
           // Main window is created, set 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.
           const permissions: Array<Permissions> = ['ohos.permission.READ_CALENDAR'];
           AtManager.requestPermissionsFromUser(context, permissions).then((data) => {
               console.info(`[requestPermissions] data: ${JSON.stringify(data)}`);
               let grantStatus: Array<number> = data.authResults;
               if (grantStatus[0] === -1) {
                   // The authorization fails.
               } else {
                   // The authorization is successful.
               }
           }).catch((err) => {
               console.error(`[requestPermissions] Failed to start request permissions. Error: ${JSON.stringify(err)}`);
           })
           
           // ...
       }
   }
   ```
   
   Request user authorization on the UI.
   ```typescript
   import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
   import { Permissions } from '@ohos.abilityAccessCtrl';
   import common from '@ohos.app.ability.common';
   
   @Entry
   @Component
   struct Index {
     reqPermissions() {
       let context = getContext(this) as common.UIAbilityContext;
       let AtManager = abilityAccessCtrl.createAtManager();
       // The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization.
       const permissions: Array<Permissions> = ['ohos.permission.READ_CALENDAR'];
       AtManager.requestPermissionsFromUser(context, permissions).then((data) => {
         console.info(`[requestPermissions] data: ${JSON.stringify(data)}`);
         let grantStatus: Array<number> = data.authResults;
         if (grantStatus[0] === -1) {
           // The authorization fails.
         } else {
           // The authorization is successful.
         }
       }).catch((err) => {
         console.error(`[requestPermissions] Failed to start request permissions. Error: ${JSON.stringify(err)}`);
       })
     }
   
     // Page display.
     build() {
       // ...
     }
   }
   ```
A
annie_wangli 已提交
199

A
Annie_wang 已提交
200
### FA Model
A
annie_wangli 已提交
201

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

```js
A
Annie_wang 已提交
205 206 207
// onWindowStageCreate() of Ability
onWindowStageCreate() {
    let context = this.context;
A
Annie_wang 已提交
208
    let array:Array<string> = ["ohos.permission.PERMISSION2"];
A
Annie_wang 已提交
209
    // The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization.
A
Annie_wang 已提交
210
    context.requestPermissionsFromUser(array).then(function(data) {
A
Annie_wang 已提交
211 212 213
        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 已提交
214
    }, (err) => {
A
Annie_wang 已提交
215
        console.error('Failed to start ability', err.code);
A
Annie_wang 已提交
216
    });
A
Annie_wang 已提交
217 218 219 220
}
```
## Pre-Authorizing user_grant Permissions
By default, the **user_grant** permissions must be dynamically authorized by the user through a dialog box. However, for pre-installed apps, you can pre-authroize 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 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 已提交
221

A
Annie_wang 已提交
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
- **bundleName**: bundle name of the application.
- `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).
- **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 vaue **false** means the opposite.

> **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 已提交
246
```
A
Annie_wang 已提交
247
<!--no_check-->