Feedback

WebWebNode.jsReact NativePhoneGapJavaScriptJavaScript V4 Security with Access Control, AES & TLS/SSL encryption for Realtime Apps

 

These docs are for PubNub 4.0 for JavaScript which is our latest and greatest! For the docs of the older versions of the SDK, please check PubNub 3.0 for JavaScript, PubNub 3.0 for NodeJS and PubNub 3.0 for PhoneGap.

If you have questions about the PubNub for JavaScript SDK, please contact us at support@pubnub.com.

 
Requires that the Access Manager add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
 

To enable SSL/TLS please check this section and to use AES please check this section.

OperationPermission required
Subscribe To Channel/ChannelGroup
Read permission on the subscribe channel
Subscribe To presence Channel/ChannelGroup
Read permission on the presence channel
Unsubscribe From Channel/ChannelGroup
Read permission on the subscribe channel
Unsubscribe From presence Channel/ChannelGroup
Read permission on the presence channel
Publish to Channel
Write permission on the subscribe channel
Here Now
Read permission on the presence channel
Where Now
Read permission on the presence channel
State
Read permission on the presence channel
History
Read permission on the subscribe channel
Add Channels to Channel Groups
Manage permission on the channel group
List Channels of Channel Groups
Manage permission on the channel group
Remove Channels from Channel Groups
Manage permission on the channel group
Remove Channel Groups
Manage permission on the channel group
PubNub provides builtin enterprise-grade security with fine-grained access control to all of your PubNub applications with PubNub Access Manager, Message Layer encryption with AES256, and Transport Layer Security with TLS and SSL. Before using this feature it must be enabled in the PubNub Admin Console.
PubNub Access Manager (PAM) extends PubNub's existing security framework by allowing developers to create and enforce secure access to channels throughout the PubNub Real Time Network. PAM provides the ability to enforce security at three different levels and in any combination of:
  • Application
  • Channel
  • Individual User
Access to a resource is granted or denied via the authorization token (aka auth key) currently set on the client.
PAM enables the developer to generate an arbitrary value for auth key using the method of his choice. This makes it possible to integrate a PubNub application with a pre-existing user authentication scheme or Security Authority.
As an example, OAuth and Facebook Connect both provide their own authentication token that could be re-used as a PAM auth key. Alternatively, a user's uuid (taken from a pre-existing DB) could also be re-used (or hashed) and used as the PAM auth key.
Your application would then use PAM grant or revoke functionality to enable or disable access to a particular channel based on the value of the connecting PubNub client's auth key.
The figure below demonstrates the use of a Security Authority leveraging PubNub Access Manager API to administer application privileges and delegate authorization tokens to users:
PubNub Access Manager
  • Security Authority issues a PAM grant to allow privileges based on a custom authentication token.
  • User requests authorization from Security Authority.
  • Security Authority delegates auth Key to user.
  • User sends credentials to PubNub and subscribes to channel.
  • PubNub verifies user privileges and sends waiting messages.
PAM operates via a grant-only (whitelist) permission scheme, where the first grant (rule) found in the hierarchy "wins". Permissions are evaluated for both publish and subscribe based on this hierarchy:
  • Subscribe key level - (access for all users on all channels)
  • Channel level - (access granted for any user but only one specific channel)
  • Channel & authorization key (access granted to specific user(s) on a given channel)
It is important to note that the more broad levels override the more granular levels -- this makes sense if you think about it as "the first matching rule wins". For example, privileges granted on an app's Subscription Key always take precedence over privileges granted on a channel or Authorization Key. Additionally, when Access Manager is first enabled there are no pre-existing permissions granted, so all read (subscribe) and write (publish) attempts to a channel will fail until explicitly granted (implicit whitelist).
Advanced Encryption Standard (AES) is a specification for the encryption of electronic data. It provides a symmetric encryption functionality (via a shared cipherKey) strong enough to be certified for use by the U.S. government for Top Secret level information.
PubNub client libraries offer built-in AES 256-bit encryption. Data is encrypted at the time of publish, before it is received by the PubNub Real-Time Network, and remains encrypted as it is routed through multiple data centers and regions. This means that unencrypted data never leaves a trusted authority, providing for full circle data encryption.
The complexity of encrypting and decrypting the data is built into the PubNub client libraries (since our libraries are open source, you are welcome to see how we did it). Encryption and decryption between all PubNub client libraries is fully supported. For example, publish encrypted from Ruby, receive the data, and decrypt on Android, iOS, and JavaScript.
 
It is important that the cipherKey is kept secret and that the key is never exchanged over the network unencrypted.
Transport Layer Security (TLS) and it's predecessor Secure Socket Layer (SSL) are methods of encrypting messages while in transport across the Internet. Using PubNub TLS/SSL ensures that client messages are protected when being sent to and from the PubNub Real-Time network. This prevents intercepted messages from being viewed by unauthorized parties.
Just enable TLS/SSL at client instance initialization, and the PubNub API takes care of the rest.
With TLS/SSL enabled, your data is encrypted as it travels through the Internet, but is decrypted, processed, and encrypted again, as it passes through the PubNub network, and back out again. This is a limitation of TLS/SSL. To ensure the highest levels of message integrity TLS/SSL should be used in combination with PubNub Message Level Encryption with AES to guarantee end-to-end data security.

Using PubNub Access Manager (PAM) requires initializing your instance with the secretKey ONLY if you intend on performing administrative PAM functions, such as granting and revoking. If your client instance will only be performing PAM consumer functions, such as subscribing, history/storage calls, publishing, etc, then you will not need to initialize with the secretKey.

 

Anyone with the secretKey can grant and revoke permissions to your app. Never let your secretKey be discovered, and to only exchange it / deliver it securely. Only use the secretKey on secure environments such as node.js application or other server-side platforms.

When you init with secretKey, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.

var pubnub = new PubNub({
    subscribeKey: "mySubscribeKey",
    publishKey: "myPublishKey",
    secretKey: "secretKey"
})
Remember, initializing with the secretKey is only necessary if this instance will be performing grant or revoke operations.
You can set a default auth key at instantiation time using the auth attribute:
var pubnub = new PubNub({
    subscribeKey: "mySubscribeKey",
    publishKey: "myPublishKey",
    authKey: "my_AuthKey"
});
From this point on, all PubNub operations will make requests using my_authkey for the auth key.
If at any point during runtime the auth key should need to be reset, you can call the setAuthKey() method to set it again:
pubnub.setAuthKey("my_authkey")
From this point on, all PubNub operations will make requests using my_newauthkey for the auth key.
In order for the PAM consumer to operate correctly, an Administrative authority (normally a server) must first issue the appropriate permissions for a given PAM channel/auth token combination.
In order to perform these administrative functions, you must initialize with at least your subscribe and secret keys:
var pubnub = new PubNub({
    subscribeKey: "mySubscribeKey",
    publishKey: "myPublishKey",
    secretKey: "secretKey"
});
All PAM operations occur at either:
  • a global level (no auth key, and no channel/channel group is defined)
  • a channel/channel group level (only a channel/channel group is defined)
  • a channel/channel group and key level (where both the channel/channel group and key are defined).
The first defined rule to match wins. To begin, lets make a blanket no read, no write, no manage access at a global level rule:
pubnub.grant(
    {
        read: false, // false to disallow
        write: false, // false to disallow
        manage: false // false to disallow
    },
    function (status) {
        // handle status
    }
);
The above states that the rule is good for 60 minutes, and that read and write are denied at the global level. The revoke() method aliases to the grant() method, but with default read and write false, so we can issue the same exact operation using revoke() as:
pubnub.grant(
    {
        channels: [''],
        read: false, // false to disallow
        write: false, // false to disallow
        manage: false // false to disallow
    },
    function (status) {
        // handle status
    }
);
Next, we can grant read-only permissions for anyone trying to perform read actions (subscribe, history, etc) but only on the public channel:
pubnub.grant(
    {
        channels: ['public_chat'],
        read: true, // false to disallow
        write: false, // false to disallow
        manage: false // false to disallow
    },
    function (status) {
        // handle status
    }
);
And for those with the auth token of authenticateduser, they can both read and write (publishes) to the public chat:
pubnub.grant(
    {
        authKeys: ['authenticateduser'],
        channels: ['public_chat'],
        read: true, // false to disallow
        write: true, // false to disallow
        ttl: 0
    },
    function (status) {
        // handle status
    }
);
 
If there is an error performing PAM operations, you may receive a 403 error. If you do, be sure you have set the correct secretKey, and the issuing computer's clock is synced with NTP.
Once your grants are in place, if during normal operation the client is denied access to a resource due to a PAM issue, the client will receive a 403 Permission Denied response from the server. From within this error response will be a JSON object, describing which resource was denied.
For example, when subscribing to a channel or list of channels including the channel topSecret, if the client is not authorized to read from topSecret per his current auth token, you will receive this error object via your error callback:
{
    "message" : "Forbidden",
    "payload" : {
        "channels" : ["pam"]
    }
}
It can be easily handled by taking action on the error callback based on the channel name defined in channels object of the error object:
pubnub.subscribe({
    channels: ['privateChat']
})
When granting or revoking permissions based on channel groups vs. channels, just use the channel_group attribute instead of the channel attribute in your PAM call as needed.
When working with Channel Groups with PAM, keep in mind these important points:
  • write permissions on a channel group is not defined / implemented
  • read permissions on a channel group are completely seperate from the read permissions on the underlying channels -- that is, if you denied read on CH1, added CH1 to channel group CG1, and granted access to read on CG1, the deny on CH1 is ignored, since you are accessing it through the channel group, which is granted read true.
  • an additional manage permission is available, which enabled or disables the ability to add/remove channels to/from a channel group.
var channelGroup = "family";

pubnub.grant(
    {
        channelGroups: [channelGroup],
        authKeys: [key1, key2],
        ttl: 12313, // 0 for infinite
        read: true, // false to disallow
        write: true, // false to disallow
        manage: true // false to disallow
    },
    function (status) {
        // handle status
    }
);
pubnub.grant(
    {
        channelGroups: [channelGroup],
        authKeys: [key1, key2],
        read: false, // false to disallow
        write: false, // false to disallow
        manage: false // false to disallow
    },
    function (status) {
        // handle status
    }
);
In order to use AES encryption, you can initialize with a default cipherKey:
var pubnub = new PubNub({
    subscribeKey: "mySubscribeKey",
    publishKey: "myPublishKey",
    cipherKey: "myCipherKey"
})
 
Anyone with the cipherKey can read the data going to and from your app if they have access to it. Although enabling TLS/SSL decreases the chances of this, its still possible given someone clever enough with enough time on their hands. Never let your cipherKey be discovered, and be sure to only exchange it / deliver it securely. On JavaScript, this means explicitly don't allow anyone to View Source or View Generated Source or Debug to enable viewing your cipherKey.
Once the cipherKey is set on a client, all encrypting and decrypting is automatic for all methods.
If the wrong cipherKey is used when receiving encrypted data, the non-decipherable ciphertext will be passed straight through to the message callback as the native base64 encoded string ciphertext string that was received.
Enabling TLS/SSL is as easy as setting the ssl attribute to true in your instance initialization:
var pubnub = new PubNub({
	subscribeKey: "mySubscribeKey",
	publishKey: "myPublishKey",
	cipherKey: "myCipherKey",
	authKey: "myAuthKey",
	logVerbosity: true,
	uuid: "myUniqueUUID",
	ssl: true,
	presenceTimeout: 130
})
Once in production, its best practice to enable SSL.
Check out PubNub's other JavaScript-based SDKs, such as JavaScript V4, Node.js V4.