harmony 鸿蒙@ohos.abilityAccessCtrl (Application Access Control)

  • 2025-06-12
  • 浏览 (4)

@ohos.abilityAccessCtrl (Application Access Control)

The abilityAccessCtrl module provides APIs for application permission management, including authentication and authorization.

NOTE
The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.

Modules to Import

import { abilityAccessCtrl } from '@kit.AbilityKit'

abilityAccessCtrl.createAtManager

createAtManager(): AtManager

Creates an AtManager instance for application access control.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Security.AccessToken

Return value

Type Description
AtManager AtManager instance created.

Example

let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();

AtManager

Provides APIs for application access control.

checkAccessToken9+

checkAccessToken(tokenID: number, permissionName: Permissions): Promise<GrantStatus>

Checks whether a permission is granted to an application. This API uses a promise to return the result.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Security.AccessToken

Parameters

Name Type Mandatory Description
tokenID number Yes Identifier of the target application, which is the value of accessTokenId contained in ApplicationInfo.
permissionName Permissions Yes Permission to check. For details about the permission, see Application Permissions.

Return value

Type Description
Promise<GrantStatus> Promise used to return the permission grant state.

Error codes

For details about the error codes, see Access Control Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100001 Invalid parameter. The tokenID is 0, or the permissionName exceeds 256 characters.

Example

import { abilityAccessCtrl } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
let tokenID: number = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a third-party application.
atManager.checkAccessToken(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS').then((data: abilityAccessCtrl.GrantStatus) => {
  console.log(`checkAccessToken success, data->${JSON.stringify(data)}`);
}).catch((err: BusinessError) => {
  console.error(`checkAccessToken fail, err->${JSON.stringify(err)}`);
});

checkAccessTokenSync10+

checkAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus

Checks whether a permission is granted to an application. This API returns the result synchronously.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Security.AccessToken

Parameters

Name Type Mandatory Description
tokenID number Yes Identifier of the target application, which is the value of accessTokenId contained in ApplicationInfo.
permissionName Permissions Yes Permission to check. For details about the permission, see Application Permissions.

Return value

Type Description
GrantStatus Permission grant state.

Error codes

For details about the error codes, see Access Control Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100001 Invalid parameter. The tokenID is 0, or the permissionName exceeds 256 characters.

Example

import { abilityAccessCtrl, Permissions } from '@kit.AbilityKit';

let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
let tokenID: number = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a third-party application.
let permissionName: Permissions = 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS';
let data: abilityAccessCtrl.GrantStatus = atManager.checkAccessTokenSync(tokenID, permissionName);
console.log(`data->${JSON.stringify(data)}`);

on18+

on(type: ‘selfPermissionStateChange’, permissionList: Array<Permissions>, callback: Callback<PermissionStateChangeInfo>): void

Subscribes to changes in the state of the specified permissions for this application.

Multiple callbacks can be registered for the same permission list.

The same callback cannot be registered for overlapping permission lists.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.Security.AccessToken

Parameters

Name Type Mandatory Description
type string Yes Event type. The value is ‘selfPermissionStateChange’, which indicates the changes in the permission states specific to this application alone.
permissionList Array<Permissions> Yes List of target permissions. If this parameter is not specified, this API will subscribe to state changes of all permissions for this application. For details about the permissions, see Application Permissions.
callback Callback<PermissionStateChangeInfo> Yes Callback used to return the permission state change.

Error codes

For details about the error codes, see Access Control Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100001 Invalid parameter. The permissionName exceeds 256 characters.
12100004 The API is used repeatedly with the same input.
12100005 The registration time has exceeded the limitation.
12100007 The service is abnormal.

Example

import { abilityAccessCtrl, Permissions } from '@kit.AbilityKit';

let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
let permissionList: Array<Permissions> = ['ohos.permission.APPROXIMATELY_LOCATION'];
try {
    atManager.on('selfPermissionStateChange', permissionList, (data: abilityAccessCtrl.PermissionStateChangeInfo) => {
        console.log('receive permission state change, data:' + JSON.stringify(data));
    });
} catch(err) {
    console.error(`catch err->${JSON.stringify(err)}`);
}

off18+

off(type: ‘selfPermissionStateChange’, permissionList: Array&lt;Permissions&gt;, callback?: Callback&lt;PermissionStateChangeInfo&gt;): void

Unsubscribes from changes in the state of the specified permissions for this application.

If callback is not specified, this API will unregister all callbacks for permissionList.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.Security.AccessToken

Parameters

Name Type Mandatory Description
type string Yes Event type. The value is ‘selfPermissionStateChange’, which indicates the changes in the permission states specific to this application alone.
permissionList Array&lt;Permissions&gt; Yes List of target permissions. The value must be the same as that in on(). If this parameter is not specified, this API will unsubscribe from state changes for all permissions. For details about the permissions, see Application Permissions.
callback Callback&lt;PermissionStateChangeInfo&gt; No Callback to unregister.

Error codes

For details about the error codes, see Access Control Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100001 Invalid parameter. The permissionNames in the list are all invalid.
12100004 The API is not used in pair with ‘on’.
12100007 The service is abnormal.

Example

import { abilityAccessCtrl, Permissions } from '@kit.AbilityKit';

let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
let permissionList: Array<Permissions> = ['ohos.permission.APPROXIMATELY_LOCATION'];
try {
    atManager.off('selfPermissionStateChange', permissionList);
} catch(err) {
    console.error(`catch err->${JSON.stringify(err)}`);
}

requestPermissionsFromUser9+

requestPermissionsFromUser(context: Context, permissionList: Array&lt;Permissions&gt;, requestCallback: AsyncCallback&lt;PermissionRequestResult&gt;): void

Requests user authorization in a dialog box opened by a UIAbility. This API uses an asynchronous callback to return the result.

If the user rejects to grant the permission, the authorization dialog box cannot be displayed again. If required, the user can manually grant the permission on the Settings page. Alternatively, call requestPermissionOnSetting to display the permission settings dialog box for the user to grant the permission.

NOTE

Only UIAbility is supported.

Atomic service API: This API can be used in atomic services since API version 12.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Security.AccessToken

Parameters

Name Type Mandatory Description
context Context Yes Context of the UIAbility that requests the permission.
permissionList Array&lt;Permissions&gt; Yes Permissions to request. For details about the permissions, see Application Permissions.
requestCallback AsyncCallback&lt;PermissionRequestResult&gt; Yes Callback used to return the result.

Error codes

For details about the error codes, see Access Control Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100001 Invalid parameter. The context is invalid when it does not belong to the application itself.

Example

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility. For details about the process and example of applying for user authorization, see Requesting User Authorization.

import { abilityAccessCtrl, Context, PermissionRequestResult, common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
let context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext;
atManager.requestPermissionsFromUser(context, ['ohos.permission.CAMERA'], (err: BusinessError, data: PermissionRequestResult) => {
  if (err) {
    console.error(`requestPermissionsFromUser fail, err->${JSON.stringify(err)}`);
  } else {
    console.info('data:' + JSON.stringify(data));
    console.info('data permissions:' + data.permissions);
    console.info('data authResults:' + data.authResults);
    console.info('data dialogShownResults:' + data.dialogShownResults);
  }
});

requestPermissionsFromUser9+

requestPermissionsFromUser(context: Context, permissionList: Array&lt;Permissions&gt;): Promise&lt;PermissionRequestResult&gt;

Requests user authorization in a dialog box opened by a UIAbility. This API uses a promise to return the result.

If the user rejects to grant the permission, the authorization dialog box cannot be displayed again. If required, the user can manually grant the permission on the Settings page. Alternatively, call requestPermissionOnSetting to display the permission settings dialog box for the user to grant the permission.

NOTE

Only UIAbility is supported.

Atomic service API: This API can be used in atomic services since API version 11.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Security.AccessToken

Parameters

Name Type Mandatory Description
context Context Yes Context of the UIAbility that requests the permission.
permissionList Array&lt;Permissions&gt; Yes Permissions to request. For details about the permissions, see Application Permissions.

Return value

Type Description
Promise&lt;PermissionRequestResult&gt; Promise used to return the result.

Error codes

For details about the error codes, see Access Control Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100001 Invalid parameter. The context is invalid when it does not belong to the application itself.

Example

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility. For details about the process and example of applying for user authorization, see Requesting User Authorization.

import { abilityAccessCtrl, Context, PermissionRequestResult, common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
let context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext;
atManager.requestPermissionsFromUser(context, ['ohos.permission.CAMERA']).then((data: PermissionRequestResult) => {
  console.info('data:' + JSON.stringify(data));
  console.info('data permissions:' + data.permissions);
  console.info('data authResults:' + data.authResults);
  console.info('data dialogShownResults:' + data.dialogShownResults);
}).catch((err: BusinessError) => {
  console.error('data:' + JSON.stringify(err));
});

requestPermissionOnSetting12+

requestPermissionOnSetting(context: Context, permissionList: Array&lt;Permissions&gt;): Promise&lt;Array&lt;GrantStatus&gt;&gt;

Requests permissions in a Settings dialog box. This API displays a permission settings dialog box for a UIAbility/UIExtensionAbility to grant permissions the second time.

Before calling this API, the application must have called requestPermissionsFromUser. If the user grants the permissions required when the authorization dialog box is displayed the first time, calling this API will not display the permission settings dialog box.

NOTE

This API supports only UIAbilities/UIExtensionAbilities.

Atomic service API: This API can be used in atomic services since API version 12.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Security.AccessToken

Parameters

Name Type Mandatory Description
context Context Yes Context of the UIAbility/UIExtensionAbility that requests the permissions.
permissionList Array&lt;Permissions&gt; Yes Permissions to request. For details about the permissions, see Application Permission Groups.

Return value

Type Description
Promise&lt;Array&lt;GrantStatus&gt;&gt; Promise used to return the authorization result.

Error codes

For details about the error codes, see Access Control Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100001 Invalid parameter. Possible causes: 1. The context is invalid because it does not belong to the application itself; 2. The permission list contains the permission that is not declared in the module.json file; 3. The permission list is invalid because the permissions in it do not belong to the same permission group.
12100010 The request already exists.
12100011 All permissions in the permission list have been granted.
12100012 The permission list contains the permission that has not been revoked by the user.

Example For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

import { abilityAccessCtrl, Context, common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
let context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext;
atManager.requestPermissionOnSetting(context, ['ohos.permission.CAMERA']).then((data: Array<abilityAccessCtrl.GrantStatus>) => {
  console.info('data:' + JSON.stringify(data));
}).catch((err: BusinessError) => {
  console.error('data:' + JSON.stringify(err));
});

requestGlobalSwitch12+

requestGlobalSwitch(context: Context, type: SwitchType): Promise&lt;boolean&gt;

Displays a dialog box for setting a global switch.

When the features such as recording and photographing are disabled, the application can call this API to open the dialog box, asking the user to enable the related features. If the global switch is turned on, no dialog box will be displayed.

NOTE

This API supports only UIAbilities/UIExtensionAbilities.

Atomic service API: This API can be used in atomic services since API version 12.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Security.AccessToken

Parameters

Name Type Mandatory Description
context Context Yes Context of the UIAbility/UIExtensionAbility.
type SwitchType Yes Type of the global switch.

Return value

Type Description
Promise&lt;boolean&gt; Promise used to return the global switch status.

Error codes

For details about the error codes, see Access Control Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
12100001 Invalid parameter. Possible causes: 1. The context is invalid because it does not belong to the application itself; 2. The type of global switch is not support.
12100010 The request already exists.
12100013 The specific global switch is already open.

Example For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

import { abilityAccessCtrl, Context, common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
let context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext;
atManager.requestGlobalSwitch(context, abilityAccessCtrl.SwitchType.CAMERA).then((data: Boolean) => {
  console.info('data:' + JSON.stringify(data));
}).catch((err: BusinessError) => {
  console.error('data:' + JSON.stringify(err));
});

verifyAccessTokenSync9+

verifyAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus

Verifies whether a permission is granted to an application. This API returns the result synchronously.

System capability: SystemCapability.Security.AccessToken

Parameters

Name Type Mandatory Description
tokenID number Yes Identifier of the target application, which is the value of accessTokenId contained in ApplicationInfo.
permissionName Permissions Yes Permission to verify. For details about the permission, see Application Permissions.

Return value

Type Description
GrantStatus Permission grant state.

Error codes

For details about the error codes, see Access Control Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
12100001 Invalid parameter. The tokenID is 0, or the permissionName exceeds 256 characters.

Example

import { abilityAccessCtrl } from '@kit.AbilityKit';

let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
let tokenID: number = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a third-party application.
try {
  let data: abilityAccessCtrl.GrantStatus = atManager.verifyAccessTokenSync(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS');
  console.log(`data->${JSON.stringify(data)}`);
} catch(err) {
  console.error(`catch err->${JSON.stringify(err)}`);
}

verifyAccessToken9+

verifyAccessToken(tokenID: number, permissionName: Permissions): Promise&lt;GrantStatus&gt;

Verifies whether a permission is granted to an application. This API uses a promise to return the result.

NOTE

You are advised to use checkAccessToken.

System capability: SystemCapability.Security.AccessToken

Parameters

Name Type Mandatory Description
tokenID number Yes Identifier of the target application, which is the value of accessTokenId contained in ApplicationInfo.
permissionName Permissions Yes Permission to verify. For details about the permission, see Application Permissions.

Return value

Type Description
Promise&lt;GrantStatus&gt; Promise used to return the authorization result.

Example

import { abilityAccessCtrl, Permissions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
let tokenID: number = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a third-party application.
let permissionName: Permissions = 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS';
atManager.verifyAccessToken(tokenID, permissionName).then((data: abilityAccessCtrl.GrantStatus) => {
  console.log(`promise: data->${JSON.stringify(data)}`);
}).catch((err: BusinessError) => {
  console.error(`verifyAccessToken fail, err->${JSON.stringify(err)}`);
});

verifyAccessToken(deprecated)

verifyAccessToken(tokenID: number, permissionName: string): Promise&lt;GrantStatus&gt;

Verifies whether a permission is granted to an application. This API uses a promise to return the result.

NOTE

This API is no longer maintained since API version 9. Use checkAccessToken instead.

System capability: SystemCapability.Security.AccessToken

Parameters

Name Type Mandatory Description
tokenID number Yes Identifier of the target application, which is the value of accessTokenId contained in ApplicationInfo.
permissionName string Yes Permission to verify. For details about the permission, see Application Permissions.

Return value

Type Description
Promise&lt;GrantStatus&gt; Promise used to return the authorization result.

Example

import { abilityAccessCtrl } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
let tokenID: number = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a third-party application.
atManager.verifyAccessToken(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS').then((data: abilityAccessCtrl.GrantStatus) => {
  console.log(`promise: data->${JSON.stringify(data)}`);
}).catch((err: BusinessError) => {
  console.error(`verifyAccessToken fail, err->${JSON.stringify(err)}`);
});

GrantStatus

Enumerates the permission grant states.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Security.AccessToken

Name Value Description
PERMISSION_DENIED -1 The permission is not granted.
PERMISSION_GRANTED 0 The permission is granted.

SwitchType12+

Enumerates the global switch types.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Security.AccessToken

Name Value Description
CAMERA 0 Global switch of the camera.
MICROPHONE 1 Global switch of the microphone.
LOCATION 2 Global switch of the location service.

PermissionStateChangeType18+

Enumerates the operations that trigger permission state changes.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.Security.AccessToken

Name Value Description
PERMISSION_REVOKED_OPER 0 Operation to revoke a permission.
PERMISSION_GRANTED_OPER 1 Operation to grant a permission.

PermissionStateChangeInfo18+

Represents the permission state change details.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.Security.AccessToken

Name Type Read Only Optional Description
change PermissionStateChangeType Yes No Operation that triggers the permission state change.
tokenID number Yes No Identifier of the target application, which is the value of accessTokenId contained in ApplicationInfo.
permissionName Permissions Yes No Permissions whose authorization state changes. For details about the permissions, see Application Permissions.

PermissionRequestResult10+

type PermissionRequestResult = _PermissionRequestResult

Represents the permission request result.

Atomic service API: This API can be used in atomic services since API version 11.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Security.AccessToken

Type Description
_PermissionRequestResult Permission request result object.

Context10+

type Context = _Context

Represents the context for the ability or application. It allows access to application-specific resources.

Atomic service API: This API can be used in atomic services since API version 11.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Security.AccessToken

Type Description
_Context Context for an ability or application to access to application-specific resources.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Ability Kit

harmony 鸿蒙AbilityAccessControl

harmony 鸿蒙AbilityBase

harmony 鸿蒙AbilityBase_Element

harmony 鸿蒙AbilityRuntime

harmony 鸿蒙bundle

harmony 鸿蒙OH_NativeBundle_ApplicationInfo

harmony 鸿蒙OH_NativeBundle_ElementName

harmony 鸿蒙ability_access_control.h

harmony 鸿蒙ability_base_common.h

0  赞