On this page

Access Manager v3 API for JavaScript SDK

Access Manager isn't enabled by default
Without it, PubNub resources on this keyset have no access controls and clients can reach channels and metadata without permission checks — including Publish, Subscribe, and all other operations. Enable Access Manager in Admin Portal before deploying to production.

Access Manager allows you to enforce security controls for client access to resources within the PubNub Platform. With Access Manager v3, your servers (that use a PubNub instance configured with a secret key) can grant their clients tokens with embedded permissions that provide access to individual PubNub resources:

  • For a limited period of time.
  • Through resource lists or patterns (regular expressions).
  • In a single API request, even if permission levels differ (read to channel1 and write to channel2).

You can add the authorizedUuid parameter to the grant request to restrict the token usage to one client with a given userId. Once specified, only this authorizedUuid will be able to use the token to make API requests for the specified resources, according to permissions given in the grant request.

User ID / UUID

User ID is also referred to as UUID/uuid in some APIs and server responses but holds the value of the userId parameter you set during initialization.

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 token

Requires Access Manager add-on

This method requires that the Access Manager add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

Requires Secret Key authentication

Granting permissions to resources should be done by administrators whose SDK instance has been initialized with a Secret Key (available on the Admin Portal on your app's keyset).

Not available in web/browser builds

The pre-built web/browser bundle of the JavaScript SDK (including the CDN version) disables the Access Manager (PAM) module at build time for security reasons. Calling grantToken() in a browser environment will fail with "PAM module disabled". Use a server-side Node.js application to grant tokens, then pass them to the browser client using setToken(). For more details, refer to Configuration — Server Operations.

The grantToken() method generates a time-limited authorization token with an embedded access control list. The token defines time to live (ttl), authorized_uuid, and a set of permissions giving access to one or more resources:

  • channels
  • groups (channel groups)
  • users (DataSync User objects)
  • uuids (App Context UUID metadata, such as names or avatars)
  • dataSync (DataSync entities, relationships, and memberships)
Don't mix uuids with users

users and uuids are separate token scopes: DataSync checks users, while App Context checks uuids. The SDK nevertheless accepts only one of them in a single grantToken() call, and the check spans the whole request, so resources.users cannot be combined with patterns.uuids. Mixing them fails validation before anything is sent.

channels and spaces are the preferred and deprecated names for the same channel scope. authorizedUserId and authorized_uuid likewise name the client allowed to use the token. This alias relationship does not apply to users and uuids.

Everything else combines freely, so one token can grant users, channels, groups, and dataSync together. Use uuids only for App Context UUID metadata permissions.

Only this authorized_uuid will be able to use the token with the defined permissions. The authorized client will send the token to PubNub with each request until the token's ttl expires. Any unauthorized request or a request made with an invalid token will return a 403 with a respective error message.

The grant request allows your server to securely grant your clients access to the resources within the PubNub Platform. There is a limited set of operations the clients can perform on every resource:

ResourcePermissions
channel
read, write, get, manage, update, join, delete
group
read, manage
users
create, get, update, delete
uuids (deprecated)
get, update, delete
dataSync (entities, relationships, memberships)
create, get, update, delete

For permissions and API operations mapping, refer to Manage Permissions with Access Manager v3.

DataSync user and channel objects are protected through the users and channels resource types, not through a separate DataSync scope. A grant under uuids does not authorize DataSync user operations. Only DataSync entities, relationships, and memberships use the dataSync scope. Refer to DataSync access control for the full permission and resource-type mapping.

read, write, manage, and join stay messaging concepts and are not available on users or on any dataSync resource.

Method(s)

1pubnub.grantToken({
2 ttl: number,
3 authorizedUserId: string,
4 resources: any,
5 patterns: any,
6 meta: any,
7 dataSyncProjections: any
8})
* required
ParameterDescription
ttl *
Type: number
Default:
n/a
Total number of minutes for which the token is valid.
  • The minimum allowed value is 1.
  • The maximum is 43,200 minutes (30 days).
authorizedUserId
Type: string
Default:
n/a
Single user ID which is authorized to use the token to make API requests to PubNub.
authorized_uuid
Type: string
Default:
n/a
Deprecated alias of authorizedUserId. Cannot be combined with it.
resources
Type: any
Default:
n/a
Object containing resource permissions.
resources.users
Type: any
Default:
n/a
Object containing user permissions keyed by user ID, for example: {"user-alice": {create: true, get: true, update: true, delete: true},"user-bob": {...}}. Covers DataSync User objects. Cannot be combined with uuids.
resources.uuids
Type: any
Default:
n/a
App Context UUID metadata permissions, for example: {"uuid-1": {get: true, update: true, delete: true},"uuid-2": {...}}. Does not authorize DataSync users and cannot be combined with users in one SDK call.
resources.channels
Type: any
Default:
n/a
Object containing channel permissions, for example: {"channel-id-1": {read: true, write: true, manage: true, delete: true, get: true, update: true, join: true},"channel-id-2": {...}}.
resources.groups
Type: any
Default:
n/a
Object containing channel group permissions, for example: {"group-id-1": {read: true, manage: true},"group-id-2": {...}}.
resources.dataSync
Type: any
Default:
n/a
Object containing DataSync resource permissions.
resources.dataSync.entities
Type: any
Default:
n/a
Object containing entity permissions keyed by entity id, for example: {"product-sneaker-42": {create: true, get: true, update: true, delete: true},"product-sneaker-43": {...}}.
resources.dataSync.relationships
Type: any
Default:
n/a
Object containing relationship permissions keyed by relationship id, for example: {"relationship-id-1": {create: true, get: true, update: true, delete: true},"relationship-id-2": {...}}.
resources.dataSync.memberships
Type: any
Default:
n/a
Object containing membership permissions keyed by membership id, for example: {"membership-id-1": {create: true, get: true, update: true, delete: true},"membership-id-2": {...}}.
patterns
Type: any
Default:
n/a
Object containing permissions to multiple resources specified by a RegEx pattern.
patterns.users
Type: any
Default:
n/a
Object containing user permissions to apply to all user IDs matching the RegEx pattern, for example: {"user-.*": {create: true, get: true, update: true, delete: true},"guest-.*": {...}}. Cannot be combined with uuids.
patterns.uuids
Type: any
Default:
n/a
App Context UUID metadata permissions for matching IDs, for example: {"uuid-pattern-1": {get: true, update: true, delete: true},"uuid-pattern-2": {...}}. Does not authorize DataSync users and cannot be combined with users in one SDK call.
patterns.channels
Type: any
Default:
n/a
Object containing channel permissions to apply to all channels matching the RegEx pattern, for example: {"channel-pattern-1": {read: true, write: true, manage: true, delete: true, get: true, update: true, join: true}, "channel-pattern-2": {...}}.
patterns.groups
Type: any
Default:
n/a
Object containing channel group permissions to apply to all channel groups matching the pattern, for example: {"group-pattern-1": {read: true, manage: true}, "group-pattern-2": {...}}.
patterns.dataSync
Type: any
Default:
n/a
Object containing DataSync resource permissions to apply to all resources matching the RegEx pattern.
patterns.dataSync.entities
Type: any
Default:
n/a
Object containing entity permissions to apply to all entities matching the RegEx pattern, for example: {"product-.*": {create: true, get: true, update: true, delete: true},"order-.*": {...}}.
patterns.dataSync.relationships
Type: any
Default:
n/a
Object containing relationship permissions to apply to all relationships matching the RegEx pattern, for example: {"owner-.*": {create: true, get: true, update: true, delete: true},"member-.*": {...}}.
patterns.dataSync.memberships
Type: any
Default:
n/a
Object containing membership permissions to apply to all memberships matching the RegEx pattern, for example: {"seat-.*": {create: true, get: true, update: true, delete: true},"sub-.*": {...}}.
meta
Type: any
Default:
n/a
Extra metadata to be published with the request. Values must be scalar only; arrays or objects aren't supported.
dataSyncProjections
Type: any
Default:
n/a
Object assigning field-level projections to DataSync resources. Refer to the projections rows below.
dataSyncProjections.resources
Type: any
Default:
n/a
Projection assignments for exact resource ids. Holds entities, relationships, users, channels, and memberships maps of id to projection name, for example: {entities: {"product-sneaker-42": "public"}, users: {"user-alice": "public"}}.
dataSyncProjections.patterns
Type: any
Default:
n/a
Projection assignments keyed by RegEx pattern. Holds entities, relationships, users, channels, and memberships maps of pattern to projection name, for example: {entities: {"product-.*": "public"}, channels: {"room-.*": "public"}}.

Projections control which payload fields a token can read and write on a DataSync resource. Each id (or pattern) maps to one projection name, __default__ is the built-in base projection, and exact id assignments take priority over pattern matches. Refer to the DataSync projections guide for how a token selects a projection.

A projection is declared per property on the class definition, so the names you can assign here are the ones the entity class or relationship class declares. A class allows at most three distinct projection names in total, including __default__, so at most two custom names besides __default__.

Projections cover users and channels, permissions don't

dataSyncProjections accepts all five resource kinds, entities, relationships, users, channels, and memberships. Permissions are split differently: resources.dataSync and patterns.dataSync accept only entities, relationships, and memberships, because DataSync users and channels are permissioned through the top-level users and channels scopes. So to give a token read access to a DataSync user through a named projection, grant users and assign the projection under dataSyncProjections.

Projections filter real-time events too. The event delivered on an object's plain (__default__) channel carries only the fields declared under __default__, and the event delivered on a __{projection}__{id} channel carries only the fields declared under that projection. status is filtered the same way. id, eTag, createdAt, updatedAt, and expiresAt are always delivered unfiltered, and delete events are never filtered. Refer to Add DataSync listener.

Required key/value mappings

For a successful grant request, you must specify permissions for at least one user, channel, or group, a DataSync resource, or a dataSyncProjections assignment, either as a resource sequence (resources) or as a regular expression (patterns).

Sample code

Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
1

1

Returns

1"p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI"

Other examples

Grant an authorized client different levels of access to various resources in a single call

The code below grants my-authorized-uuid:

  • Read access to channel-a, channel-group-b, and get to uuid-c.
  • Read/write access to channel-b, channel-c, channel-d, and get/update to uuid-d.
1

Grant an authorized client read access to multiple channels using RegEx

The code below grants my-authorized-uuid read access to all channels that match the channel-[A-Za-z0-9] RegEx pattern.

1

Grant an authorized client different levels of access to various resources and read access to channels using RegEx in a single call

The code below grants the my-authorized-uuid:

  • Read access to channel-a, channel-group-b, and get to uuid-c.
  • Read/write access to channel-b, channel-c, channel-d, and get/update to uuid-d.
  • Read access to all channels that match the channel-[A-Za-z0-9] RegEx pattern.
1

Grant an authorized client access to DataSync resources

The code below grants user-alice:

  • Get access to the entity product-sneaker-42, and to all entities matching the product-.* RegEx pattern.
  • Get access to the DataSync user user-bob through the top-level users scope, because DataSync users are not permissioned under dataSync.
1

Grant a token with a field-level projection

The code below grants user-alice the same access as above and assigns the public projection to the entity product-sneaker-42 and to the user user-bob. With those projections, Alice reads and writes only the fields that the public projection exposes on each object.

1

Error responses

If you submit an invalid request, the server returns the 400 error status code with a descriptive message informing which of the provided arguments is missing or incorrect. These can include, for example, issues with a RegEx, a timestamp, or permissions. The server returns the details of the error in the JSON format.

Revoke token

Enable token revoke

This method requires that the Access Manager add-on is enabled for your key in the Admin Portal. Also, to revoke tokens, you must first enable this feature. To do that, navigate to your app's keyset and mark the Revoke v3 Token checkbox in the ACCESS MANAGER section.

The revokeToken() method allows you to disable an existing token and revoke all permissions embedded within. You can only revoke a valid token previously obtained using the grantToken() method.

Use this method for tokens with ttl less than or equal to 30 days. If you need to revoke a token with a longer ttl, contact support.

For more information, refer to Revoke permissions.

Method(s)

1pubnub.revokeToken(
2 token: string
3);
* required
ParameterDescription
token *
Type: string
Default:
n/a
Existing token with embedded permissions.

Sample code

1

Returns

When the token revocation request is successful, this method returns a 200 OK.

Error Responses

If you submit an invalid request, the server returns an error status code with a descriptive message informing which of the provided arguments is missing or incorrect. Depending on the root cause, this operation may return the following errors:

  • 400 Bad Request
  • 403 Forbidden
  • 503 Service Unavailable

Parse token

The parseToken() method decodes an existing token and returns the object containing permissions embedded in that token. The client can use this method for debugging to check the permissions to the resources or find out the token's ttl details.

Method(s)

1pubnub.parseToken(
2 token: string
3)
* required
ParameterDescription
token *
Type: string
Default:
n/a
Current token with embedded permissions.

Sample code

1

Returns

1{
2 "version":2,
3 "timestamp":1629394579,
4 "ttl":15,
5 "authorized_uuid": "user1",
6 "resources":{
7 "uuids":{
8 "user1":{
9 "read":false,
10 "write":false,
11 "manage":false,
12 "delete":false,
13 "get":true,
14 "update":true,
15 "join":false
show all 76 lines

DataSync permissions and projections

A token granted with users or with dataSync permissions decodes those scopes as well. DataSync scopes carry only the four CRUD flags, and projections come back under meta on the pn-projections key, where each entry is a composite datasync:<kind>:<id> key mapped to the projection name:

1{
2 "version":2,
3 "timestamp":1629394579,
4 "ttl":15,
5 "authorized_uuid":"user-alice",
6 "resources":{
7 "users":{
8 "user-bob":{ "create":false, "get":true, "update":false, "delete":false }
9 },
10 "dataSync":{
11 "entities":{
12 "product-sneaker-42":{ "create":false, "get":true, "update":false, "delete":false }
13 }
14 }
15 },
show all 29 lines

The dataSync, users, and meta keys appear only when the token actually granted them, so guard the access when you read one.

Error Responses

If you receive an error while parsing the token, it may suggest that the token is damaged. In that case, request the server to issue a new one.

Set token

The setToken() method is used by the client devices to update the authentication token granted by the server.

Method(s)

1pubnub.setToken(
2 token: string
3)
* required
ParameterDescription
token *
Type: string
Default:
n/a
Current token with embedded permissions.

Sample code

1

Returns

This method doesn't return any response value.

Grant token - spaces & users (deprecated)

Deprecated

This method is deprecated and will be removed in a future version. Please use the grantToken() method instead.

Requires Access Manager add-on

This method requires that the Access Manager add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

Server only operation

Granting a token requires the SDK to be initialized with a secretKey and should only be used on the server. You should not use a secretKey in client SDKs such as React Native and Web. For more details on server usage, see Access Manager.

The grantToken() method generates a time-limited authorization token with an embedded access control list. The token defines time to live (ttl), authorizedUserId, and a set of permissions giving access to one or more resources:

  • spaces
  • users (other users' metadata, such as their names or avatars)

Only this authorizedUserId will be able to use the token with the defined permissions. The authorized client will send the token to PubNub with each request until the token's ttl expires. Any unauthorized request or a request made with an invalid token will return a 403 with a respective error message.

Permissions - spaces & users (deprecated)

The grant request allows your server to securely grant your clients access to the resources within the PubNub Platform. There is a limited set of operations the clients can perform on every resource:

ResourcePermissions
space
read, write, get, manage, update, join, delete
user
get, update, delete

For permissions and API operations mapping, refer to Manage Permissions with Access Manager v3.

TTL - spaces & users (deprecated)

The ttl (time to live) parameter is the number of minutes before the granted permissions expire. The client will require a new token to be granted before expiration to ensure continued access. ttl is a required parameter for every grant call and there is no default value set for it. The max value for ttl is 43,200 (30 days).

Recommended ttl value

For security reasons, it's recommended to set ttl between 10 and 60, and create a new token before this ttl elapses.

For more details, see TTL in Access Manager v3.

RegEx - spaces & users (deprecated)

If you prefer to specify permissions by setting patterns, rather than listing all resources one by one, you can use regular expressions. To do this, set RegEx permissions as patterns before making a grant request.

For more details, see RegEx in Access Manager v3.

Authorized user ID - spaces & users (deprecated)

Setting an authorizedUserId in the token helps you specify which client device should use this token in every request to PubNub. This will ensure that all requests to PubNub are authorized before PubNub processes them. If authorizedUserId isn't specified during the grant request, the token can be used by any client with any userId. It's recommended to restrict tokens to a single authorizedUserId to prevent impersonation.

For more details, see Authorized UUID in Access Manager v3.

Method(s) - spaces & users (deprecated)

1pubnub.grantToken({
2 ttl: number,
3 authorizedUserId: string,
4 resources: any,
5 patterns: any,
6 meta: any
7})
* required
ParameterDescription
ttl *
Type: number
Default:
n/a
Total number of minutes for which the token is valid.
  • The minimum allowed value is 1.
  • The maximum is 43,200 minutes (30 days).
authorizedUserId
Type: string
Default:
n/a
Single userId which is authorized to use the token to make API requests to PubNub.
resources
Type: any
Default:
n/a
Object containing resource permissions.
resources.users
Type: any
Default:
n/a
Object containing User permissions, for example: {"userId-1": {get: true, update: true, delete: true},"userId-2": {...}}.
resources.spaces
Type: any
Default:
n/a
Object containing Space permissions, for example: {"space-id-1": {read: true, write: true, manage: true, delete: true, get: true, update: true, join: true},"space-id-2": {...}}.
patterns
Type: any
Default:
n/a
Object containing permissions to multiple resources specified by a RegEx pattern.
patterns.users
Type: any
Default:
n/a
Object containing User permissions to apply to all Users matching the RegEx pattern, for example: {"userId-pattern-1": {get: true, update: true, delete: true},"userId-pattern-2": {...}}.
patterns.spaces
Type: any
Default:
n/a
Object containing Space permissions to apply to all Spaces matching the RegEx pattern, for example: {"space-pattern-1": {read: true, write: true, manage: true, delete: true, get: true, update: true, join: true}, "space-pattern-2": {...}}.
meta
Type: any
Default:
n/a
Extra metadata to be published with the request. Values must be scalar only; arrays or objects aren't supported.
Required key/value mappings

For a successful grant request, you must specify permissions for at least one userId or space, either as a resource sequence (resources) or as a regular expression (patterns).

Sample code - spaces & users (deprecated)

1try {
2 const token = await pubnub.grantToken({
3 ttl: 15,
4 authorizedUserId: "my-authorized-userId",
5 resources: {
6 spaces: {
7 "my-space": {
8 read: true,
9 },
10 },
11 },
12 });
13} catch (status) {
14 console.log(status);
15}

Returns - spaces & users (deprecated)

1"p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI"

Other examples - spaces & users (deprecated)

Grant an authorized client different levels of access to various resources in a single call - spaces & users (deprecated)

The code below grants my-authorized-userId:

  • Read access to space-a, and get to userId-c.
  • Read/write access to space-b, space-c, space-d, and get/update to userId-d.
1try {
2 const token = await pubnub.grantToken({
3 ttl: 15,
4 authorizedUserId: "my-authorized-userId",
5 resources: {
6 spaces: {
7 "space-a": {
8 read: true,
9 },
10 "space-b": {
11 read: true,
12 write: true,
13 },
14 "space-c": {
15 read: true,
show all 36 lines
Grant an authorized client read access to multiple channels using RegEx - spaces & users (deprecated)

The code below grants my-authorized-userId read access to all channels that match the space-[A-Za-z0-9] RegEx pattern.

1try {
2 const token = await pubnub.grantToken({
3 ttl: 15,
4 authorizedUserId: "my-authorized-userId",
5 patterns: {
6 spaces: {
7 "^space-[A-Za-z0-9]$": {
8 read: true,
9 },
10 },
11 },
12 });
13} catch (status) {
14 console.log(status);
15}
Grant an authorized client different levels of access to various resources and read access to channels using RegEx in a single call - spaces & users (deprecated)

The code below grants the my-authorized-userId:

  • Read access to space-a and userId-c.
  • Read/write access to space-b, space-c, space-d, and get/update to userId-d.
  • Read access to all channels that match the space-[A-Za-z0-9] RegEx pattern.
1try {
2 const token = await pubnub.grantToken({
3 ttl: 15,
4 authorizedUserId: "my-authorized-userId",
5 resources: {
6 spaces: {
7 "space-a": {
8 read: true,
9 },
10 "space-b": {
11 read: true,
12 write: true,
13 },
14 "space-c": {
15 read: true,
show all 43 lines

Error responses - spaces & users (deprecated)

If you submit an invalid request, the server returns the 400 error status code with a descriptive message informing which of the provided arguments is missing or incorrect. These can include, for example, issues with a RegEx, a timestamp, or permissions. The server returns the details of the error in the JSON format.