• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Verifying API Access Permissions
2
3## When to Use
4
5To protect sensitive data and eliminate security threats 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.
6
7## Available APIs
8
9The following describes only the API used for permission verification. For more information about the APIs, see [Application Access Control](../reference/apis/js-apis-abilityAccessCtrl.md).
10
11checkAccessToken(tokenID: number, permissionName: Permissions): Promise<GrantStatus>
12
13| Name  | Type                | Mandatory| Description                                      |
14| -------- | -------------------  | ---- | ------------------------------------------ |
15| tokenID   |  number   | Yes  | Token ID of the application. You can obtain the value from the [ApplicationInfo](../reference/apis/js-apis-bundleManager-applicationInfo.md) of the application.            |
16| permissionName | Permissions | Yes  | Name of the permission to verify. Valid permission names are defined in the [Application Permission List](permission-list.md).|
17
18
19## Example
20
21The procedure is as follows:
22
231. Obtain the caller's identity (**tokenId**).
24   > **NOTE**
25   >
26   > You can use **getCallingTokenId** to obtain the caller's **tokenId**. For details, see [RPC](../reference/apis/js-apis-rpc.md).
272. Determine the permission to verify, which is **ohos.permission.ACCELEROMETER** in this example.
283. Call **checkAccessToken()** to perform a permission verification for the caller.
294. Proceed based on the permission verification result.
30
31```ts
32  import abilityAccessCtrl from '@ohos.abilityAccessCtrl'
33  import { BusinessError } from '@ohos.base';
34  import rpc from '@ohos.rpc'
35
36  class Stub extends rpc.RemoteObject {
37      onRemoteMessageRequest(code: number, data: rpc.MessageSequence, reply: rpc.MessageSequence, option: rpc.MessageOption) {
38          let callerTokenId: number = rpc.IPCSkeleton.getCallingTokenId();
39          console.log("RpcServer: getCallingTokenId result: " + callerTokenId);
40          let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
41          try {
42              atManager.checkAccessToken(callerTokenId, "ohos.permission.ACCELEROMETER").then((data: abilityAccessCtrl.GrantStatus) => {
43                  console.log(`checkAccessToken success, data->${JSON.stringify(data)}`);
44              }).catch((err: BusinessError) => {
45                  console.log(`checkAccessToken fail, err->${JSON.stringify(err)}`);
46              });
47          } catch(err) {
48              console.log(`catch err->${JSON.stringify(err)}`);
49          }
50          return true;
51      }
52  }
53```
54