• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.userIAM.userAccessCtrl (User Access Control) (System API)
2
3The **userAccessCtrl** module provides APIs for setting and obtaining user identity authentication policies and verifying user identity authentication results.
4
5> **NOTE**
6>
7> The initial APIs of this module are supported since API version 16. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8
9## Modules to Import
10
11```ts
12import { userAccessCtrl } from '@kit.UserAuthenticationKit';
13```
14
15## AuthTokenType
16
17Enumerates the authentication token types.
18
19**System capability**: SystemCapability.UserIAM.UserAuth.Core
20
21**System API**: This is a system API.
22
23| Name                     | Value  | Description      |
24| ------------------------ | ---- | ---------- |
25| TOKEN_TYPE_LOCAL_AUTH    | 0    | Authentication token issued based on the local authentication result.|
26| TOKEN_TYPE_LOCAL_RESIGN  | 1    | Authentication token issued based on the reused identity authentication result.|
27| TOKEN_TYPE_COAUTH        | 2    | Authentication token issued based on a collaborative authentication result of multiple devices.|
28
29## AuthToken
30
31Represents the AuthToken data returned after a successful verification.
32
33**System capability**: SystemCapability.UserIAM.UserAuth.Core
34
35**System API**: This is a system API.
36
37| Name          | Type                              | Read Only| Optional| Description                                      |
38| -------------- | ---------------------------------- | ----- | ----- |------------------------------------------------------------ |
39| challenge | Uint8Array | No| No|Random challenge for the authentication.|
40| authTrustLevel | [userAuth.AuthTrustLevel](js-apis-useriam-userauth.md#authtrustlevel8) | No| No|Authentication trust level.|
41| authType | [userAuth.UserAuthType](js-apis-useriam-userauth.md#userauthtype8) | No| No |Credential type for the identity authentication.|
42| tokenType | [AuthTokenType](#authtokentype) | No| No|Authentication token type.|
43| userId | number | No| No |User ID.|
44| timeInterval | bigint | No | No |Time elapsed since the issuance of the authentication token, in milliseconds.|
45| secureUid | bigint    | No | Yes |Secure user ID.|
46| enrolledId | bigint   | No | Yes |Credential enrollment ID.|
47| credentialId | bigint | No | Yes |Credential ID.|
48
49
50## userAccessCtrl.verifyAuthToken
51
52verifyAuthToken(authToken: Uint8Array, allowableDuration: number): Promise\<AuthToken>
53
54Verifies an authentication token.
55
56**Required permissions**: ohos.permission.USE_USER_ACCESS_MANAGER
57
58**System capability**: SystemCapability.UserIAM.UserAuth.Core
59
60**System API**: This is a system API.
61
62**Parameters**
63
64| Name    | Type                       | Mandatory| Description      |
65| ---------- | --------------------------- | ---- | ---------- |
66| authToken | Uint8Array | Yes  | Authentication token to verify, which cannot exceed 1024.|
67| allowableDuration  | number  | Yes  | Time allowed for the authentication token to be used after being issued, in milliseconds. The value must be greater than 0 and less than or equal to 86,400,000.|
68
69**Return value**
70
71| Type                                     | Description        |
72| ----------------------------------------- | ------------ |
73| Promise\<[AuthToken](#authtoken)> | Promise used to return the parsed authentication token.|
74
75**Error codes**
76
77For details about the error codes, see [User Authentication Error Codes](errorcode-useriam.md).
78
79| ID| Error Message                               |
80| -------- | --------------------------------------- |
81| 201      | Permission verification failed.         |
82| 202      | The caller is not a system application. |
83| 401      | Incorrect parameters. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.    |
84| 12500002 | General operation error.                |
85| 12500015 | AuthToken integrity check failed.     |
86| 12500016 | AuthToken has expired.                |
87
88**Example**
89
90```ts
91import { BusinessError } from '@kit.BasicServicesKit';
92import { cryptoFramework } from '@kit.CryptoArchitectureKit';
93import { userAccessCtrl } from '@kit.UserAuthenticationKit';
94import { userAuth } from '@kit.UserAuthenticationKit';
95
96try {
97  const rand = cryptoFramework.createRandom();
98  const allowableDuration: number = 5000;
99  const len: number = 16;
100  const randData: Uint8Array = rand?.generateRandomSync(len)?.data;
101  const authParam: userAuth.AuthParam = {
102    challenge: randData,
103    authType: [userAuth.UserAuthType.PIN],
104    authTrustLevel: userAuth.AuthTrustLevel.ATL3,
105  };
106  const widgetParam: userAuth.WidgetParam = {
107    title: 'Enter password',
108  };
109
110  const userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
111  console.info('get userAuth instance success');
112  // The authentication result is returned by onResult() only after the authentication is started by start() of UserAuthInstance.
113  userAuthInstance.on('result', {
114    onResult (result) {
115        if (!result.token) {
116            console.error('userAuthInstance callback result.token is null');
117            return;
118        }
119        // Initiate a request for verifying the authentication token.
120        userAccessCtrl.verifyAuthToken(result.token, allowableDuration)
121            .then((retAuthToken: userAccessCtrl.AuthToken) => {
122                Object.keys(retAuthToken).forEach((key) => {
123                    console.info(`retAuthToken key:${key}, value:${retAuthToken[key]}`);
124                })
125            }).catch ((error: BusinessError) => {
126                console.error(`verify authToken error. Code is ${error?.code}, message is ${error?.message}`);
127            })
128    }
129  });
130  console.info('auth on success');
131  // Start authentication.
132  userAuthInstance.start();
133  console.info('auth start success');
134} catch (error) {
135  const err: BusinessError = error as BusinessError;
136  console.error(`auth catch error. Code is ${err?.code}, message is ${err?.message}`);
137}
138```
139