Objective-CiOSiOSCocoaiOS Security with Access Control, AES & TLS/SSL encryption for Realtime Apps

Requires the Access Manager add-on to be enabled for your key. To enable add-on features for your keys, refer to 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 channel
Where Now
Read permission on the presence channel
Read permission on the channel
Read permission on the subscribe channel
Add Channels to Channel Groups
Manage permission on the channel group
List Channels of Channel Groups
Read 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 hiearcht "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 'cipher key') 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 cipher key 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 your data is encrypted as it travels through the Internet, but it must be encrypted (and re-encrypted) as it passes through the PubNub servers 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 secret key can grant and revoke permissions to your app. Never let your secret key be discovered, and 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 secret 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
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).
If there is an error performing PAM operations, you may receive a 403 error. If you do, be sure you have set the correct secret key, and the issuing computer's clock is synced with NTP.
In order to use AES encryption, you can initialize with a default cipher key:
PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"demo" 
configuration.uuid = @"myUniqueUUID";
configuration.cipherKey = @"my_cipherkey";
self.client = [PubNub clientWithConfiguration: configuration];
Anyone with the cipher key 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 cipher key 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 cipher key.
Once the cipher key is set on a client, all encrypting and decrypting is automatic for all methods.
You can use encryption helper if you want a part of the message to be encrypted:
 Subscription process results arrive to listener which should adopt to PNObjectEventListener protocol
 and registered using:
[self.client addListener:self];
[self.client subscribeToChannels:@[@"my_channel"] withPresence:YES];

// Handle new message from one of channels on which client has been subscribed.
- (void)client:(PubNub *)client didReceiveMessage:(PNMessageResult *)message {
	// Handle new message stored in message.data.message
	if (![message.data.channel isEqualToString:message.data.subscription]) {
		// Message has been received on channel group stored in message.data.subscription.
	else {

		// Message has been received on channel stored in message.data.channel.
	// Handle new message stored in message.data.message
	NSDictionary *messagePayload = message.data.message;
	NSString *publicMessage = messagePayload[@"public"];
	NSString *encryptedMessage = messagePayload[@"secret"];
	NSData *messageData = [PNAES decrypt:encryptedMessage withKey:@"my_cipherkey"];
	if (messageData) {
		NSString *decryptedMessage = [[NSString alloc] initWithData:messageData encoding:NSUTF8StringEncoding];
		NSLog(@"Received message on channel %@ at %@\nPublic: %@\nSecret:\n\tEncrypted: %@\n\tDecrypted: %@", 
			  message.data.channel, message.data.timetoken, publicMessage, encryptedMessage, decryptedMessage);

// Handle subscription status change.
- (void)client:(PubNub *)client didReceiveStatus:(PNStatus *)status {

	if (status.operation == PNSubscribeOperation) {
		// Check whether received information about successful subscription or restore.
		if (status.category == PNConnectedCategory || status.category == PNReconnectedCategory) {
			// Status object for those categories can be casted to `PNSubscribeStatus` for use below.
			PNSubscribeStatus *subscribeStatus = (PNSubscribeStatus *)status;
			if (subscribeStatus.category == PNConnectedCategory) {
				// This is expected for a subscribe, this means there is no error or issue whatsoever.
				// Prepare 'secret' message.
				NSString *message = @"No one should see me as plain";
				NSData *messageData = [message dataUsingEncoding:NSUTF8StringEncoding];
				NSString *secretMessage = [PNAES encrypt:messageData withKey:@"my_cipherkey"];
				NSString *targetChannel = [client channels].lastObject;
				[client publish:@{@"public": @"Everyone can see me as plain", @"secret": secretMessage} 
					  toChannel:targetChannel compressed:NO withCompletion:^(PNPublishStatus *publishStatus) {
						// Check whether request successfully completed or not.
						if (!publishStatus.isError) {

							// Message successfully published to specified channel.
						else {

							 Handle message publish error. Check 'category' property to find out 
							 possible reason because of which request did fail.
							 Review 'errorData' property (which has PNErrorData data type) of status
							 object to get additional information about issue.
							 Request can be resent using: [publishStatus retry];
			else {
				 This usually occurs if subscribe temporarily fails but reconnects. This means there was 
				 an error but there is no longer any issue.
		else if (status.category == PNUnexpectedDisconnectCategory) {
			 This is usually an issue with the internet connection, this is an error, handle 
			 appropriately retry will be called automatically.
		// Looks like some kind of issues happened while client tried to subscribe or disconnected from 
		// network.
		else {
			PNErrorStatus *errorStatus = (PNErrorStatus *)status;
			if (errorStatus.category == PNAccessDeniedCategory) {
				 This means that PAM does allow this client to subscribe to this channel and channel group 
				 configuration. This is another explicit error.
			else {
				 More errors can be directly specified by creating explicit cases for other error categories 
				 of `PNStatusCategory` such as: `PNDecryptionErrorCategory`,  
				 `PNMalformedFilterExpressionCategory`, `PNMalformedResponseCategory`, `PNTimeoutCategory`
				 or `PNNetworkIssuesCategory`
Enabling TLS/SSL is as easy as setting the TLSEnabled attribute to true in your instance initialization:
 Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"demo" 
configuration.TLSEnabled = YES;
configuration.uuid = @"myUniqueUUID";
self.client = [PubNub clientWithConfiguration:configuration];
Once in production, its best practice to enable SSL.