提交 56878855 编写于 作者: A Annie_wang

update docs

Signed-off-by: NAnnie_wang <annie.wangli@huawei.com>
上级 67f5007d
......@@ -2,8 +2,8 @@
- Access Control
- [Access Control (Permission) Overview](accesstoken-overview.md)
- [Permission Application Guide](accesstoken-guidelines.md)
- [API Access Permission Verification](permission-verify-guidelines.md)
- [Applying for Permissions](accesstoken-guidelines.md)
- [Verifying API Access Permissions](permission-verify-guidelines.md)
- [Application Permission List](permission-list.md)
- User Authentication
- [User Authentication Overview](userauth-overview.md)
......
# Permission Application Guide
# Applying for Permissions
## When to Use
......@@ -13,24 +13,26 @@ This document describes the following operations:
## Declaring Permissions in the Configuration File
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.
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.
> **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).
> **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).
The following table describes the fields in the configuration file.
| Field | Mandatory| Description |
| --------- | -------- | ------------------------------------------------------------ |
| name | Yes | Name of the permission. |
| 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.|
| 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.|
| 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.|
### Stage Model
If your application is based on the stage model, declare the required permissions in [**module.json5**](../quick-start/module-configuration-file.md).
If your application is developed based on the stage model, declare the required permissions in [**module.json5**](../quick-start/module-configuration-file.md).
```json
{
......@@ -64,7 +66,7 @@ If your application is based on the stage model, declare the required permission
### FA Model
If your application is based on the FA model, declare the required permissions in **config.json**.
If your application is developed based on the FA model, declare the required permissions in **config.json**.
```json
{
......@@ -98,9 +100,9 @@ If your application is based on the FA model, declare the required permissions i
## Declaring the ACL
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.
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.
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).
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).
```json
{
......@@ -116,49 +118,103 @@ For example, if an application needs to access audio files of a user and capture
## Requesting User Authorization
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.
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.
**Figure 1** Requesting authorization from a user
![](figures/permission-read_calendar.png)
> **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.
> **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.
### Stage Model
Example: Request the permission for an application to access calendar information.
Example: Apply for the permission for an application to access the Calendar.
1. Apply for the **ohos.permission.READ_CALENDAR** permission. For details, see [Declaring Permissions in the Configuration File](#declaring-permissions-in-the-configuration-file).
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).
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.
2. Check whether the user has granted the permission.
Request user authorization in UIAbility.
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;
// 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}`);
}
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:
```typescript
import UIAbility from '@ohos.app.ability.UIAbility';
import window from '@ohos.window';
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
const permissions: Array<Permissions> = ['ohos.permission.READ_CALENDAR'];
export default class EntryAbility extends UIAbility {
// ...
onWindowStageCreate(windowStage: window.WindowStage) {
// Main window is created, set main page for this ability
// 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.
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;
let length: number = grantStatus.length;
for (let i = 0; i < length; i++) {
if (grantStatus[i] !== 0) {
// The authorization fails.
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(`[requestPermissions] Failed to start request permissions. Error: ${JSON.stringify(err)}`);
console.error(`requestPermissionsFromUser failed, code is ${err.code}, message is ${err.message}`);
})
// ...
......@@ -166,32 +222,34 @@ Example: Request the permission for an application to access calendar informatio
}
```
Request user authorization on the UI.
Sample code for requesting user authorization on the UI:
```typescript
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import common from '@ohos.app.ability.common';
const permissions: Array<Permissions> = ['ohos.permission.READ_CALENDAR'];
@Entry
@Component
struct Index {
reqPermissions() {
reqPermissionsFromUser(permissions: Array<Permissions>): void {
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;
let length: number = grantStatus.length;
for (let i = 0; i < length; i++) {
if (grantStatus[i] !== 0) {
// The authorization fails.
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(`[requestPermissions] Failed to start request permissions. Error: ${JSON.stringify(err)}`);
console.error(`requestPermissionsFromUser failed, code is ${err.code}, message is ${err.message}`);
})
}
......@@ -202,6 +260,27 @@ Example: Request the permission for an application to access calendar informatio
}
```
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) => {
// ...
})
}
```
### FA Model
Call [requestPermissionsFromUser()](../reference/apis/js-apis-inner-app-context.md#contextrequestpermissionsfromuser7) to request user authorization.
......@@ -223,10 +302,10 @@ reqPermissions() {
}
```
## 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 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:
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:
- **bundleName**: bundle name of the application.
- **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).
- **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 value **false** means the opposite.
> **NOTE**<br>This file is available only for preinstalled applications.
......
# API Access Permission Verification
# Verifying API Access Permissions
## When to Use
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册