permission-verify-guidelines.md 2.2 KB
Newer Older
A
Annie_wang 已提交
1
# API Access Permission Verification
A
Annie_wang 已提交
2 3 4

## When to Use

A
Annie_wang 已提交
5
To protect sensitive data and eliminate security threads on core abilities, you can use the permissions in the [Application Permission List](permission-list.md) to protect the related API from unauthorized calling. Each time before the API is called, a permission verification is performed to check whether the caller has the required permission.
A
Annie_wang 已提交
6 7 8

## Available APIs

A
Annie_wang 已提交
9
The table below lists only the API used for access permission verification. For more information, see [AbilityContext](../reference/apis/js-apis-ability-context.md).
A
Annie_wang 已提交
10 11 12 13 14 15 16 17 18 19 20

| API                                                      | Description                                            |
| ------------------------------------------------------------ | --------------------------------------------------- |
| verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> | Checks whether an application process has the specified permission.|


## Example

The procedure is as follows:

1. Obtain the caller's identity (**tokenId**).
A
Annie_wang 已提交
21 22 23
   > **NOTE**
   > 
   > You can use **getCallingTokenId** to obtain the caller's **tokenId**. For details, see [RPC](../reference/apis/js-apis-rpc.md#getcallingtokenid8).
A
Annie_wang 已提交
24
2. Determine the permission to verify, which is **ohos.permission.PERMISSION** in this example.
A
Annie_wang 已提交
25
3. Call **verifyAccessToken()** to perform a permission verification for the caller.
A
Annie_wang 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
4. Proceed based on the permission verification result.

```js
  import abilityAccessCtrl from '@ohos.abilityAccessCtrl'
  import rpc from '@ohos.rpc'

  class Stub extends rpc.RemoteObject {
      onRemoteRequest(code, data, reply, option) {
          let callerTokenId = rpc.IPCSkeleton.getCallingTokenId();
          console.log("RpcServer: getCallingTokenId result: " + callerTokenId);
          var atManager = abilityAccessCtrl.createAtManager();
          var result = await atManager.verifyAccessToken(tokenID, "ohos.permission.PERMISSION");
          if (result == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
            // Allow the caller to invoke the API provided by the app.
          } else {
            // Deny the caller's access to the API.
          }
          return true;
      }
  }

```