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 or subscribe operation works until you provide an authorization token to the PubNub object. If you provide an invalid token, the requesting client receives a Forbidden error.
To learn more about Access Manager, see 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 permissions for each channel, channelGroup, and uuid resource. For common permissions, a single request is usually enough.
Privileges granted to an application's subscribeKey always take precedence over privileges granted to channel or auth Key. An application that requires authentication at the user level must not grant access at the Application or Channel levels. See Grant levels.
Permissions
The grant request allows your server to grant access to 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 the mapping of permissions to API operations, see 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 used wildcards to grant permissions to a.*.
Grant levels
When a user attempts to access a PubNub resource, Access Manager evaluates the existing rules in this order of precedence before it grants access to a channel:
- Application Level - Access Manager privileges are always evaluated first at the
Applicationlevel. If thereadorwriteattribute istruefor asubscribeKey, Access Manager grants access for that attribute immediately and doesn't check theChannelorUserlevels. 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
truefor a combination ofsubscribeKeyandchannel, Access Manager grants access for that attribute at theChannellevel and doesn't check theUserlevel. - 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})
authKeys#- Specifies
authKeyto grant permissions. You can specify multipleauthkeys as a comma-separated list with a singlechannelname.authKeysare required for user-level grants. If you don't specify anauthKey, the permissions will apply to all clients on channel-level or application-level. See Grant levels. channels#- Specifies up to 200 channels on which to grant permissions. If you set none of
channels,channelGroups,uuids, orcategories, the grant applies to the whole keyset.
This parameter supports wildcards that are one level deep (a.*). channelGroups#- Specifies up to 200 channel groups on which to grant permissions. If you set none of
channels,channelGroups,uuids, orcategories, the grant applies to the whole keyset.
This parameter does not support wildcards. uuids#- Specifies up to 200 uuids on which to grant permissions. If you set none of
channels,channelGroups,uuids, orcategories, the grant applies to the whole keyset. RequiresauthKeys.
You can't grant permissions to channels and channel groups in the same request if you decide to useuuids.
This parameter does not support wildcards. categories#- Specifies the categories to grant. Valid values are
channels, which lists all channel metadata withgetAllChannelMetadata(), anduuids, which lists all uuid metadata withgetAllUUIDMetadata(). Agetpermission on a named channel or uuid doesn't imply this. RequiresauthKeys. Refer to Category permissions. ttlrequired#- Time in minutes for which granted permissions are valid. Default is
1440 (24hrs), Max is525600, Min is1. Settingttlto0will apply the grant indefinitely. read#- Set to
trueto grantreadpermissions. Set tofalseto remove permissions. write#- Set to
trueto grantwritepermissions. Set tofalseto remove permissions. manage#- Set to
trueto grantmanagepermissions. Set tofalseto remove permissions. delete#- Set to
trueto grantdeletepermissions. Set tofalseto remove permissions. get#- Set to
trueto grantgetpermissions. Set tofalseto remove permissions. update#- Set to
trueto grantupdatepermissions. Set tofalseto remove permissions. join#- Set to
trueto grantjoinpermissions. Set tofalseto 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 |
The response lists the granted categories under categories, keyed channels and uuids. Each entry holds the permissions per auth key under auths. When the request grants only categories, level is category. When it also grants channels, channel groups, or uuids, 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
grant() resolves with the payload of the service response. It does not wrap it in a status envelope.
1{
2 "ttl" : 12313,
3 "auths" : {
4 "my_authkey" : {
5 "r" : 1,
6 "w" : 1,
7 "m" : 1,
8 "d" : 1,
9 "g" : 0,
10 "u" : 0,
11 "j" : 0
12 }
13 },
14 "subscribe_key" : "my_subkey",
15 "level" : "user",
show all 17 linesA grant on uuids returns the permissions under uuids, keyed by uuid ID, in place of channel and auths. The level is uuid.
Size 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
Configure NTP on your server to keep its clock in sync. Clock drift causes a 400 Invalid Timestamp error response. See Why do I get "Invalid Timestamp" when I grant permissions?.
Other examples
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 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.
1try {
2 const result = await pubnub.grant({
3 authKeys: ["my_authkey"],
4 categories: ["channels", "uuids"],
5 get: true,
6 ttl: 15,
7 });
8 console.log("Grant response:", result);
9} catch (status) {
10 console.log(status);
11}
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}