Access Manager

Migrate from v2 to v3

This is a newly released version of Access Manager. If you already use Access Manager in v2, you need to update your configuration before you start using the new version. Read the Migration Guide for all the necessary migration steps.

When you develop an in-app messaging application, you might want to set rules that would only allow a selected user to access specific channels and user metadata. This is where Access Manager comes in. With it, you can set up a detailed permission schema for your application and decide who can do what with your data. This way you secure your application and protect it against any unauthorized third-party access attempts.

Access Manager (v3) is a cryptographic, token-based permission administrator that allows you to regulate clients' access to PubNub resources, such as channels, channel groups, and User IDs. For instance, you can make a one-to-one chat room private by only allowing two users to be able to read and write messages in this channel. Alternatively, you can make a channel public by giving all users access to it. With Access Manager, you can define multiple permissions in a single API call by listing resource groups explicitly or creating patterns with regular expressions (RegEx).

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.

Applications built with Access Manager create tokens with individual permissions for each authorized user of the application. These tokens are generated by PubNub. A client device would need to acquire an appropriate token for its user and pass the token with any request made to the PubNub API.

Configuration

To use Access Manager, you must enable and configure it on a chosen app's keyset in the Admin Portal.

Access Manager in Admin Portal

OptionDescription
Revoke v3 TokenThis feature lets you invalidate a previously issued token so that it can no longer be used to authenticate requests for access to PubNub resources.

Authorization flow

There are three actors involved in the authorization process:

  • Server - Client applications that use Access Manager require a centralized server application that keeps track of all interactions between the users and the PubNub resources they have access to. The server is solely authorized to request permission grants from PubNub. It should also expose an API through which clients can request new or updated tokens. In-app messaging applications usually have a centralized server in place to support such operations as validation of users logging in to clients. The same server can be used to implement and manage the Access Manager logic in your application.

  • Client device - A client that represents a single device where a user logs in to perform an operation supported by PubNub. For Access Manager-enabled applications, a client needs to request a token from the centralized server before making PubNub API calls and attempting to access resources such as channels, channel groups, and User ID metadata. Clients also need logic to periodically refresh their user’s token before it expires.

  • PubNub - The PubNub platform provides APIs to support both centralized server applications and client devices associated with a particular user. Server applications call the grant API to generate or refresh tokens. Client applications pass these tokens in requests to PubNub APIs (such as publish or subscribe) for PubNub to validate that the user associated with the client has the appropriate permissions.

A typical client authorization could look as follows:

Client Devices → Your Server → PN Network ← Client Devices

  1. Upon login, the client device requests authorization to be able to send requests to PubNub.

  2. The server issues a token request to PubNub by defining the permissions it needs to give to a specific authorized User ID.

  3. PubNub reads these permissions and returns a signed, self-contained, and time-limited access token to the server.

  4. The server passes the token to the client device as part of the login response.

  5. The client device adds the token to the client's SDK configuration.

  6. When the client device later makes PubNub API calls, the SDK passes the configured token. It can continue to do so until the token expires or is revoked, at which point it needs to request a new token to be issued.

Server-side operations

A centralized server is an implementation that initializes with a server-side PubNub SDK authenticated by a secretKey. Permissions grants can only be requested by a server.

Initialize with a secret key

The secretKey lets you use Access Manager to provide clients with access to PubNub resources, change access levels, and remove permissions. When you initialize PubNub with the secretKey, you get root permissions for Access Manager. With this feature, you don't have to grant access to your servers to access channel data as the servers get read and write access to all resources.

Secret key security

The secretKey should only be used within a secure server and never exposed to client devices. If the secretKey is ever compromised, it can be an extreme security risk to your application. If you suspect your secretKey has been compromised, you have the ability to regenerate a new secretKey for the existing PubNub keyset on the Admin Portal.

const pubnub = new PubNub({
subscribeKey: "mySubscribeKey",
publishKey: "myPublishKey",
secretKey: "mySecretKey",
userId: "myUniqueUserId"
});

Grant permissions

Once you've enabled Access Manager on the Admin Portal and initialized the PubNub object with a secretKey, you can assign permissions to client devices. To do this, make a call to the PubNub server in which you request it to grant a new token. Specify the authorized User ID which will use the token exclusively, its permissions to resources (provided in a sequence and/or as regular expressions), and a ttl (time to live) for the grant.

An authorized User ID can have permissions for:

  • Channels
  • Channel groups
  • User IDs (which are other users' object metadata, such as their names or avatars)

Once the grant is successful, the server responds to the client device's authentication request by returning a token with embedded permissions.

The code below grants the my-authorized-uuid:

  • Read access to channel-a, channel-group-b, and uuid-c.
  • Read/write access to channel-b, channel-c, channel-d, and uuid-d.
  • Read access to all channels that match the channel-[A-Za-z0-9] RegEx pattern.
pubnub.grantToken(
{
ttl: 15,
authorized_uuid: "my-authorized-uuid",
resources: {
channels: {
"channel-a": {
read: true
},
"channel-b": {
read: true,
write: true
},
"channel-c": {
read: true,
show all 48 lines

Token size limits

Since a token stores all access mappings, its size increases with the number of embedded permissions. The token size can impact the overall size of the HTTP request. If your PubNub request, such as publish or subscribe, exceeds 32 KiB, it will fail with the 414 URI Too Long status code response. To keep the token size within limits, use RegEx patterns rather than resource lists to set permissions, and keep the resource naming consistent. For more information, refer to channel naming convention or contact support for assistance.

TTL

The ttl parameter is the number of minutes before the granted permissions expire, at which point the client has to be re-granted the new token. ttl is a required parameter for every grant call and there is no default value set for it.

The minimum system value for ttl is 1 (1 minute) and the maximum value is 43200 (30 days). For security reasons, it's recommended to set ttl between 10 and 60 minutes. If your business case requires ttl to be higher than the allowed limit, contact support for assistance.

RegEx

You can grant an authorized UUID access to channels, channel groups, and metadata of different UUIDs in a single API call. There are two ways for doing that:

  • Provide a single resource or a sequence of resources that an authorized UUID should be able to access.
  • Grant an authorized UUID access to a pattern-based sequence of UUIDs, channels, or channel groups using regular expressions.

To make a successful grant request, you must specify permissions for at least one UUID, channel, or channel group, either as a resource sequence or as a pattern (RegEx).

Authorized UUID

For a higher level of security, you can specify one top-level authorized UUID in the grant payload. When specified, this UUID will be embedded in the token and returned by the grant request. This ensures that any request to PubNub that uses that token has to come from that authorized UUID. Otherwise, PubNub will reject the request and deny access to the resources.

Authorized UUID vs UUIDs

The grant request body contains the uuids key which defines permissions required to access the other UUIDs' (users') metadata. The UUIDs contained within have nothing to do with the UUID authorized to use the token. To allow a UUID to use a particular token, specify this UUID as an authorized one (authorized_uuid). The value of that parameter must be an instance of a preexisting client's UUID that was set during the initialization of its PubNub object. For more information about setting UUIDs, refer to Identity Management.

Change permissions

Depending on the application's logic, there might be a need to change the user's original permissions. For example, an application may dictate that a user should be added or removed from a channel in certain cases. When this occurs, the server should make a new grant request to PubNub with the updated permissions and ensure that some logic provides the appropriate client(s) with the updated token(s).

Revoke permissions

Enable token revoke

To revoke tokens, you must first enable this feature on the Admin Portal. To do that, navigate to your app's keyset and mark the Revoke v3 Token checkbox in the ACCESS MANAGER section.

Access Manager allows you to disable (revoke) a token. This means that all calls to any PubNub API that use a revoked token will fail with a 403 Revoked Token error. Revoking tokens is particularly useful when you need to quickly remove access to PubNub resources.

You can only revoke a valid token previously obtained through a token grant request. Each revoked token is stored in a deny list (usual charges apply) allowing for quick lookup of revoked tokens.

There are certain constraints to consider when revoking tokens:

  • You can only enable the token revoke feature if the token ttl for the subkey is less than or equal to 30 days. If that ttl value doesn't meet your requirements, contact support.
  • If support changes your token's ttl to exceed 30 days, you can disable the token revoke functionality, but can't re-enable it using the Admin Portal. To do that, contact support.
  • You can only revoke one token per one revoke call, batch revokes aren't supported.
  • It may take up to 1 minute for the token revoke request to take effect.
  • You can't re-enable a revoked token.
const token = await pubnub.revokeToken("p0AkFl043rhDdHRsple3KgQ3NwY6BDcENnctokenVzcqBDczaWdYIGOAeTyWGJI");

Token caching

For improved operational efficiency, PubNub caches the tokens. During the permissions check, if a token isn't present in the deny list, PubNub will cache this state for up to 1 minute.

If the token was found in the deny list, the system will cache this response for the ttl of the token.

Token expiration

Each time an authenticated request is made to the PubNub server, the server checks if the token embedded in the request is still valid. Each token has a specific ttl and once it expires, it will need to be replaced so that the client can make successful calls to PubNub. If the client sends an expired token, the PubNub server will return a 403 with a respective error message. To change or extend client device access to specific resources, you must grant a new token with modified permissions. To address the token expiration effectively, it's recommended for applications using Access Manager to have a token refresh strategy that would follow one of these approaches:

  1. The server maintains a list of expiry times, automatically refreshes soon-to-be-stale tokens, and proactively sends the new token to the clients. Clients should respond to these updates by updating the token in the SDK.

  2. Client checks the ttl whenever it receives a token and sets a timer to make a refresh request. The server supports a refresh API.

  3. Client supports the logic that handles 403 responses, makes a just-in-time refresh request, updates the SDK upon getting a new token, and retries the request that fails.

Client-side operations

In general, client applications don't generate tokens, but rather call server APIs to obtain tokens. The syntax and implementation of these client and server APIs are up to the developer. This section outlines operations that a client may take after getting a token from the centralized server applications.

Check permissions

Access Manager v3 allows you to decode your permissions by parsing a token. You don't need a secretKey to request token details.

Use this method whenever you want to:

  • Debug an issue to diagnose the reason for a failing request that returns a 403.
  • Inspect privileges embedded in the token to check if you have access to a given resource.

Request token details:

pubnub.parseToken("yourToken")

See a sample response:

{
"version":2,
"timestamp":1629394579,
"ttl":15,
"authorized_uuid": "user1",
"resources":{
"uuids":{
"user1":{
"read":false,
"write":false,
"manage":false,
"delete":false,
"get":true,
"update":true,
"join":false
show all 76 lines

Request a new token

When a client makes an API request using a token that has expired or has been revoked, PubNub API will respond with the 403 Token is expired or 403 Token revoked error message. To renew access, the client should include the logic that prompts the server to request a new token to be generated by PubNub. The authorization flow looks similar to the already described login example. In both cases the server first includes the application-specific logic to validate that the request came from an authorized client, and then makes a PubNub token grant request:

Client Devices → Your Server → PN Network ← Client Devices

After either a login or a token refresh request from the client, the server passes the newly generated token back to the client device, which then needs to update its configuration and set the new token:

pubnub.setToken("newToken")

Permissions

Access Manager v3 allows permissions to be granted for the following PubNub resources. These are the permission flags allowed for each resource:

ResourceAvailable Permissions
Channelread, write, delete, get, update, manage, join
Channel Groupread, manage
UUID Metadataget, update, delete

Operations to permissions mapping

The following tables show the mappings of API operations to resources and permissions.

Pub/Sub

PubNub OperationResourcePermission
Publish on channelChannelWrite
Signal on channelChannelWrite
Subscribe to channelChannelRead
Subscribe to presence channelPresence Channel (-pnpres)Read
Subscribe to channel groupChannel GroupRead
Subscribe to presence channel groupPresence Channel Group (-pnpres)Read
Unsubscribe from channelChannelNone required
Unsubscribe from channel groupChannel GroupNone required

Presence

PubNub OperationResourcePermission
Here NowChannelRead
Where NowChannelnone required
Get StateChannelRead
Set StateChannelRead

Message Persistence

PubNub OperationResourcePermission
History - Fetch MessagesChannelRead
Message CountsChannelRead
Delete MessagesChannelDelete

File Sharing

PubNub OperationResourcePermission
Send file on channelChannelWrite
List filesChannelRead
Download fileChannelRead
Delete fileChannelDelete

Channel groups

PubNub OperationResourcePermission
Add Channels to channel groupChannel GroupManage
Remove Channels from channel groupChannel GroupManage
List Channels in channel groupChannel GroupManage
Remove channel groupChannel GroupManage

App Context

PubNub OperationResourcePermission
Set user metadataUUIDUpdate
Delete user metadataUUIDDelete
Get user metadataUUIDGet
Get all user metadataUUIDManaged by the Disallow Get All User Metadata option in the App Context configuration on the Admin Portal.

When this option is unchecked, and Access Manager is enabled in an app, you can get metadata of all users without the need to define that in the permissions schema included in the authentication token.
Set channel metadataChannelUpdate
Delete channel metadataChannelDelete
Get channel metadataChannelGet
Get all channel metadataChannelManaged by the Disallow Get All Channel Metadata option in the App Context configuration on the Admin Portal.

When this option is unchecked, and Access Manager is enabled in an app, you can get metadata of all channels without the need to define that in the permissions schema included in the authentication token.
Set channel membersChannelManage
Remove channel membersChannelManage
Get channel membersChannelGet
Set channel membershipsChannel, UUIDChannels: Join
UUID: Update
Remove channel membershipsChannel, UUIDChannels: Join
UUID: Update
Get channel membershipsUUIDGet

Mobile Push Notifications

PubNub OperationResourcePermission
Register channel for pushChannelRead
Remove channel's push registrationChannelRead

Message Reactions

PubNub OperationResourcePermission
Add Message ActionChannelWrite
Remove Message ActionChannelDelete
Get Message ActionsChannelRead
Get History with ActionsChannelRead
Last updated on