Access Manager v2 API for JavaScript SDK
Access Manager allows you to enforce secure controls for client access to resources within the PubNub network. With Access Manager, your servers can grant their clients access to individual PubNub resources for a limited duration, with the ability to extend access or add permissions for additional resources.
As soon as Access Manager is enabled, no publish/subscribe operations can be done without first explicitly providing an authorization token to the PubNub object. If an invalid token is provided, the requesting client will receive a Forbidden error.
For more information about Access Manager, refer to Managing Permissions with Access Manager.
Supported and recommended asynchronous patterns
PubNub supports Callbacks, Promises, and Async/Await for asynchronous JS operations. The recommended pattern is Async/Await and all sample requests in this document are based on it. This pattern returns a status only on detecting an error. To receive the error status, you must add the try...catch syntax to your code.
Grant
Requires Access Manager add-on
This method requires that the Access Manager add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
The grant method allows you to grant permissions for one or more resources to one or more authKeys. You may need to make multiple grant calls with an authKey so that you can specify explicit permissions for each channel, channelGroup and uuid resources. For common permissions, you can normally use a single request.
Privileges specifically granted to an application's subscribeKey always take precedence over privileges granted to channel or auth Key. Therefore an application that requires authentication at the user level should not grant access at either the Application or Channel levels. View the Grant Levels section for more details.
Permissions
The grant request allows your server to securely grant access for your clients on the following resources within the platform. Each resource allows a limited set of permissions that control the operations that can be performed by the clients. For permissions and API operations mapping information, refer to Managing Permissions with Access Manager.
| Resource | Permissions |
|---|---|
channel | read, write, get, manage, update, join, delete |
uuid | get, update, delete |
channelGroup | read, manage |
category (channels, uuids) | get only |
In grant(), the categories parameter selects the channels and uuids categories.
- A category permission lets a token list all metadata of one resource type on your subscribe key. Valid categories are
channelsanduuids. The only permission isget(32). - A
getpermission on one named channel or user, or on a pattern, does not grant a category. - A token can contain only categories. It needs no resource or pattern.
- When enumeration enforcement is enabled for a keyset, App Context list requests from a token or auth key without the matching category permission return a
403error.
Wildcard permissions
Wildcard notation allows you to grant permissions to multiple channels at a time and later revoke these permissions in the same manner. You can go one level deep using wildcards. In other words:
a.*grants access on all channels that begin witha..*ora.b.*won't work this way. If you grant on*ora.b.*, the grant treats*ora.b.*as a channel name, not a wildcard.
Wildcard revokes
You can revoke permissions with wildcards from one level deep, like a.*, only when you initially used wildcards to grant permissions to a.*.
Grant levels
When a user attempts to access a PubNub resource, Access Manager will evaluate any existing rules using the following order of precedence before access to a channel is granted to the user:
- Application Level - Access Manager privileges are always evaluated first at the
Applicationlevel. If eitherreadorwriteattribute is set totruefor asubscribeKey, Access Manager will immediately grant access for that attribute without proceeding to check permissions at eitherChannelorUserlevels. If an attribute is set tofalseat the Application level, Access Manager proceeds to evaluate the attribute at the next most granular level. - Channel Level - After first verifying an attribute at the Application level, Access Manager evaluates the attribute at the Channel level. If an attribute is set to
truefor a combination ofsubscribeKey, andchannel, Access Manager grants access for that attribute at theChannellevel without proceeding to check whether there may beuserlevel permissions. - User Level (Recommended) - As a final step Access Manager evaluates the attributes at the
Userlevel. If an attribute is set totrueforsubscribeKey,channeland auth Key, access is granted for that attribute. Similarly, user level grants also allow you granting an auth Key access tochannelGroupsanduuids. User level grants requireauthKeysand are the recommended approach if you need to manage permissions for individual users within your application. Each user should be assigned a unique auth Key and securely passed back to the user to perform operations on the platform.
Method(s)
To Grant Permissions on a Channel, you can use the following method(s) in the JavaScript SDK
1grant({Array channels, Array channelGroups, Array uuids, Array categories, Array authKeys, Number ttl, Boolean read, Boolean write, Boolean manage, Boolean delete, Boolean get, Boolean update, Boolean join})
| Parameter | Description |
|---|---|
authKeysType: Array Default: n/a | Specifies authKey to grant permissions. It is possible to specify multiple auth keys as comma separated list in combination with a single channel name. authKeys are required for user-level grants. If you don't specify an authKey, the permissions will apply to all clients on channel-level or application-level. View the Grant Levels section for more details. |
channelsType: Array Default: n/a | Specifies up to 200 channels on which to grant permissions. If you set none of channels, channelGroups, uuids, or categories, the grant applies to the whole keyset. This parameter supports wildcards that are one level deep ( a.*). |
channelGroupsType: Array Default: n/a | Specifies up to 200 channel groups on which to grant permissions. If you set none of channels, channelGroups, uuids, or categories, the grant applies to the whole keyset. This parameter does not support wildcards. |
uuidsType: Array Default: n/a | Specifies up to 200 uuids on which to grant permissions. Requires authKeys. You can't grant permissions to channels and channel groups in the same request if you decide to use uuids. This parameter does not support wildcards. |
categoriesType: Array Default: n/a | Specifies the categories to grant. Valid values are channels, which lists all channel metadata with getAllChannelMetadata(), and uuids, which lists all uuid metadata with getAllUUIDMetadata(). A get permission on a named channel or uuid doesn't imply this. Requires authKeys. Refer to Category permissions. |
ttl *Type: Number Default: 1440 (24hrs) | Time in minutes for which granted permissions are valid. Default is 1440 (24hrs), Max is 525600 , Min is 1. Setting ttl to 0 will apply the grant indefinitely. |
readType: Boolean Default: false | Set to true to grant read permissions. Set to false to remove permissions. |
writeType: Boolean Default: false | Set to true to grant write permissions. Set to false to remove permissions. |
manageType: Boolean Default: false | Set to true to grant manage permissions. Set to false to remove permissions. |
deleteType: Boolean Default: false | Set to true to grant delete permissions. Set to false to remove permissions. |
getType: Boolean Default: false | Set to true to grant get permissions. Set to false to remove permissions. |
updateType: Boolean Default: false | Set to true to grant update permissions. Set to false to remove permissions. |
joinType: Boolean Default: false | Set to true to grant join permissions. Set to false to remove permissions. |
Category permissions
- A category permission lets a token list all metadata of one resource type on your subscribe key. Valid categories are
channelsanduuids. The only permission isget(32). - A
getpermission on one named channel or user, or on a pattern, does not grant a category. - A token can contain only categories. It needs no resource or pattern.
- When enumeration enforcement is enabled for a keyset, App Context list requests from a token or auth key without the matching category permission return a
403error.
When you set categories:
- Set
gettotrueto grant the category. Setgettofalsewith the samecategoriesandauthKeysto revoke it. - The SDK sends every permission you leave unset as
false. - The
getpermission also applies to every channel, channel group, and uuid in the same request, because all resources in a request share one set of permissions. - The SDK rejects the request before sending it if you set
read,write,manage,delete,update, orjointotrue.
The SDK returns these errors for an invalid category request:
| Cause | Error message |
|---|---|
categories is set without authKeys. | authKeys are required for grant request on categories |
categories contains a value other than channels or uuids. | Invalid category: only channels and uuids are supported |
read, write, manage, delete, update, or join is true. | Category permissions must be exactly the get permission |
ttl is 1 and get is true. | One-minute category grants are not supported |
ttl is 1 and get is true. | One-minute category grants are not supported |
The response lists the granted categories under payload.categories, keyed channels and uuids. Each entry holds the permissions per auth key under auths. When the request grants only categories, payload.level is category. When it also grants channels, channel groups, or uuids, payload.level keeps the level of those resources.
Sample code
Grant Access Manager permissions for channel and auth key
1try {
2 const result = await pubnub.grant({
3 authKeys: ["my_authkey"],
4 channels: ["my_channel"],
5 ttl: 12313, // 0 for infinite
6 read: true, // false to disallow
7 write: true, // false to disallow
8 manage: true, // false to disallow
9 delete: true, // false to disallow
10 });
11} catch (status) {
12 console.log(status);
13}
Response
1{
2 "status" : 200,
3 "message" : "Success",
4 "payload" : {
5 "ttl" : 1440,
6 "auths" : {
7 "my_authkey" : {
8 "r" : 1,
9 "w" : 1,
10 "m" : 1,
11 "d" : 1,
12 "g" : 0,
13 "u" : 0,
14 "j" : 0
15 }
show all 22 linesSize of revoke requests
Access Manager grant or revoke requests must be less than ~32 KiB at a time, or the client will return an error. For requests greater than 32 KiB, break them into smaller batched requests. When the message size exceeds 32 KiB the server returns the HTTP Error code 500, instead of the correct error code 414.
NTP configuration
For NTP synchronization, please ensure that you have configured NTP on your server to keep the clock in sync. This is to prevent system clock drift leading to 400 Invalid Timestamp error response. See Why do I get "Invalid Timestamp" when I grant permissions?.
Other examples
Grant an auth key access to list all channel and uuid metadata
The code below grants my_authkey the get category permission for both channels and uuids, with a 15 minute ttl.
1
Grant access to a channel on an authKey
Grant read permission to a channel only for clients with a specific authKey with a 5 minute ttl:
1try {
2 const result = await pubnub.grant({
3 authKeys: ["my_authkey"],
4 channels: ["my_channel"],
5 ttl: 5,
6 read: true, // false to disallow
7 write: false, // false to disallow
8 });
9} catch (status) {
10 console.log(status);
11}
Grant access to Presence channel on an authKey
Grant read and write permissions to an authKey on a presence channel with a 5 minute ttl:
1try {
2 const result = await pubnub.grant({
3 authKeys: ["my_authkey"],
4 channels: ["my_channel-pnpres"],
5 ttl: 5,
6 read: true, // false to disallow
7 write: true, // false to disallow
8 });
9} catch (status) {
10 console.log(status);
11}
Grant access to a UUID on an authKey
Grant get, update, and delete access to a uuid only for clients with a specific authKey with a 24 hour ttl:
1try {
2 const result = await pubnub.grant({
3 authKeys: ["key1"],
4 uuids: ["uuid1"],
5 ttl: 1440, // 0 for infinite
6 get: true, // false to disallow
7 update: true, // false to disallow
8 delete: true, // false to disallow
9 });
10} catch (status) {
11 console.log(status);
12}
Grant access to all channels on all authKeys
This request grants read permission to all users on all channel(s) with default ttl (1440 minutes). This rule applies on the application level and takes precedence over channel and user-level permissions.
Use application level grants with caution
When access is granted on an application level, all channels and users will have access.
Application level grants can also happen due to a bug in your code. For example, Null parameters for channels and auth-keys can cause accidental application level grants.
1const result = await pubnub.grant({
2 read: true,
3});
Grant access to a channel on all authKeys
This request grants read and write permissions to a specific channel for all users (no authKey required) with default ttl (1440 minutes). This rule applies on the channel level and takes precedence over user-level permissions.
1try {
2 const result = await pubnub.grant({
3 channels: ["my_channel"],
4 read: true, // false to disallow
5 write: true, // false to disallow
6 });
7} catch (status) {
8 console.log(status);
9}