Permission Management v2
Access Manager v3
This document describes Access Manager v2, which is an older version of Access Manager. We highly recommend that you upgrade to the latest version (v3).
To read more about the latest Access Manager v3, refer to the documentation. To upgrade from v2 to v3, refer to the Migration Guide.
Access Manager v2 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.
With Access Manager enabled, your clients must have permissions to send requests to PubNub. You can grant access to your clients from a secure server using the secretKey. These grants allow you to granularly manage the resources available to each client. For instance, you can make a one-to-one chat room private by only allowing the two users in that chat room to have read and write permissions on the chat room channel. Alternatively, you can make a channel public by allowing all users to have access to it.
Enable the Feature
Access Manager is an optional feature that can be enabled from the Admin Portal.
Authorization Flow
There are three actors involved when working with Access Manager: your server, the PubNub Platform, and client devices. The authorization flow is as follows:
- The client application requests authorization from the server during the login process.
- Your server issues a grant to allow privileges based on an authKey for the client.
- The client application sets PubNub credentials with that authKey and passes it to PubNub to perform API operations.
Login
Your server provides a means for clients to log in. When a device is successfully authenticated, the server generates an authKey for that client.
Grant
Your server makes a grant
call towards PubNub on that authKey with the list of resources and ttl
(time to live) for the grant. Once the grant is successful, the server responds to the client device's authentication request with this authKey.
PubNub API Request
The client device initializes the PubNub object with the publish and subscribe keys, and the provided authKey. The client receives the authKey from the login request.
Permissions
Access Manager allows permissions to be granted or revoked for the following PubNub resources. Certain permission flags are allowed for each resource.
Resource | Available Permissions |
---|---|
Channel | read, write, delete, get, update, manage, join |
Channel Group | read, manage |
UUID | get, update, delete |
Operations to Permissions Mapping
The following tables show the mappings of API operations to resources and permissions.
Pub/Sub
PubNub Operation | Resource | Permission |
---|---|---|
Publish on channel | Channel | Write |
Signal on channel | Channel | Write |
Subscribe to channel | Channel | Read |
Subscribe to presence channel | Presence Channel (-pnpres ) | Read |
Subscribe to channel group | Channel Group | Read |
Subscribe to presence channel group | Presence Channel Group (-pnpres ) | Read |
Unsubscribe from channel | Channel | None required |
Unsubscribe from channel group | Channel Group | None required |
Presence
PubNub Operation | Resource | Permission |
---|---|---|
Here Now | Channel | Read |
Where Now | Channel | none required |
Get State | Channel | Read |
Set State | Channel | Read |
Message Persistence
PubNub Operation | Resource | Permission |
---|---|---|
History - Fetch Messages | Channel | Read |
Message Counts | Channel | Read |
Delete Messages | Channel | Delete |
File Sharing
PubNub Operation | Resource | Permission |
---|---|---|
Send file on channel | Channel | Write |
List files | Channel | Read |
Download file | Channel | Read |
Delete file | Channel | Delete |
Channel Groups
PubNub Operation | Resource | Permission |
---|---|---|
Add Channels to channel group | Channel Group | Manage |
Remove Channels from channel group | Channel Group | Manage |
List Channels in channel group | Channel Group | Manage |
Remove channel group | Channel Group | Manage |
Channel Groups
Channel Groups should only be managed by a secure server, which already has the secret key giving it all permissions on all resources. The only exception might be a client app that acts as an administrator, where that user is manually managing channel groups for other client users.
App Context
PubNub Operation | Resource | Permission |
---|---|---|
Set user metadata | UUID | Update |
Delete user metadata | UUID | Delete |
Get user metadata | UUID | Get |
Get all user metadata | UUID | Managed 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 metadata | Channel | Update |
Delete channel metadata | Channel | Delete |
Get channel metadata | Channel | Get |
Get all channel metadata | Channel | Managed 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 members | Channel | Manage |
Remove channel members | Channel | Delete |
Get channel members | Channel | Get |
Set channel memberships | Channel, UUID | Channels: Join UUID: Update |
Remove channel memberships | Channel, UUID | Channels: Join UUID: Update |
Get channel memberships | UUID | Get |
Mobile Push Notifications
PubNub Operation | Resource | Permission |
---|---|---|
Register channel for push | Channel | Read |
Remove channel's push registration | Channel | Read |
Message Reactions
PubNub Operation | Resource | Permission |
---|---|---|
Add Message Action | Channel | Write |
Remove Message Action | Channel | Delete |
Get Message Actions | Channel | Read |
Get History with Actions | Channel | Read |
Server-side Operations
To perform grants, your server must first initialize a PubNub object using the secretKey and the publish and subscribe keys.
Initialize with secretKey
The secretKey lets you use the Grant API to grant clients access to PubNub resources. When you initialize PubNub with the 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 resources.
Secret Key Security
The secret key should only be used within a secure server and never exposed to client devices. If the secret key is ever compromised, it can be an extreme security risk to your application. If you suspect your secret key has been compromised, you have the ability to regenerate a new secret key for the existing PubNub keys set.
- Node.js
- Java
- C#
- Python
- Go
var pubnub = new PubNub({
publishKey: 'myPublishKey',
subscribeKey: 'mySubscribeKey',
secretKey: 'mySecretKey',
uuid: 'theServerUUID'
})
PNConfiguration pnconfig = new PNConfiguration();
pnconfig.setPublishKey("myPublishKey");
pnconfig.setSubscribeKey("mySubscribeKey");
pnconfig.setSecretKey("mySecretKey");
pnconfig.setUuid("theServerUUID");
PubNub pubnub = PubNub.create(pnconfig);
PNConfiguration pnconfig = new PNConfiguration();
pnconfig.PublishKey = "myPublishKey";
pnconfig.SubscribeKey = "mySubscribeKey";
pnconfig.SecretKey = "mySecretKey";
pnconfig.Uuid = "theServerUUID";
Pubnub pubnub = new Pubnub(pnconfig);
pnconfig = PNConfiguration()
pnconfig.publish_key = "myPublishKey"
pnconfig.subscribe_key = "mySubscribeKey"
pnconfig.secret_key = "mySecretKey"
pnconfig.uuid = "theServerUUID"
pubnub = PubNub(pnconfig)
pnconfig := pubnublib.NewConfig()
pnconfig.PublishKey = "myPublishKey"
pnconfig.SubscribeKey = "mySubscribeKey"
pnconfig.SecretKey = "mySecretKey"
pnconfig.Uuid = "theServerUUID"
pubnub := pubnublib.NewPubNub(pnconfig)
Grant Permissions
Use the grant
method to grant permissions on authKeys for one or more resources. You may need to make multiple grant calls for one authKey so that you can specify explicit permissions for each channel or channel group resources, but common permissions can be granted to a list of channels and channel groups in a single request.
The ttl
parameter is the number of minutes before the granted permissions expire, at which point the client will have to request to be re-granted further access (always generate a new authKey when you extend the permissions). The default is 1440 minutes, which is 24 hours.
Wildcard grants
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.
The request below grants read
and write
permission to the authentication key myAuthKey
for chats.room1
and chats.room2
channels:
- Node.js
- Java
- C#
- Python
- Go
pubnub.grant(
{
channels: ["chats.room1", "chats.room2"],
authKeys: ["myAuthKey"],
ttl: 1440,
read: true,
write: true
},
function (status) {
console.log(status);
}
);
pubnub.grant()
.channels(Arrays.asList("chats.room1", "chats.room2"))
.authKeys(Arrays.asList("myAuthKey"))
.write(true)
.read(true)
.ttl(1440)
.async(result -> { /* check result */ });
pubnub.Grant()
.Channels(new string[]{"chats.room1", "chats.room2"})
.AuthKeys(new string[] {"myAuthKey"})
.Write(true)
.Read(true)
.TTL(1440)
.Execute(new PNAccessManagerGrantResultExt(
(result, status) => {
// handle result/status
}
));
pubnub.grant()\
.channels(["chats.room1", "chats.room2"])\
.auth_keys(["myAuthKey"])\
.read(True)
.write(True)\
.sync()
res, status, err := pn.Grant()
.Channels([]string{"chats.room1", "chats.room2"})
.Read(true)
.Write(true)
.AuthKeys([]string{"myAuthKey"})
.TTL(1440)
.Execute()
fmt.Println(res, status, err)
The request below grants the read
permission to the authentication key myAuthKey
for alerts.*
channels using wildcards and to the cg_user123
channel group:
- Node.js
- Java
- C#
- Python
- Go
pubnub.grant(
{
channels: ["alerts.*"],
channelGroups: ["cg_user123"],
authKeys: ["myAuthKey"],
ttl: 1440,
read: true
},
function (status) {
console.log(status);
}
);
pubnub.grant()
.channels(Arrays.asList("alerts.*"))
.channelGroups(Arrays.asList("cg_user123"))
.authKeys(Arrays.asList("myAuthKey"))
.read(true)
.ttl(1440)
.async(result -> { /* check result */ });
pubnub.Grant()
.Channels(new string[]{"alerts.*"})
.ChannelGroups(new string[] {"cg_user123"})
.AuthKeys(new string[] {"myAuthKey"})
.Read(true)
.TTL(1440)
.Execute(new PNAccessManagerGrantResultExt(
(result, status) => {
// handle result/status
}
));
pubnub.grant()\
.channels(["alerts.*"])\
.channel_groups(["cg_user123"])\
.auth_keys(["myAuthKey"])\
.read(True)\
.sync()
res, status, err := pn.Grant()
.ChannelGroups([]string{"cg_user123"})
.Read(true)
.AuthKeys([]string{"myAuthKey"})
.TTL(1440)
.Execute()
fmt.Println(res, status, err)
The request below grants get
, update
and delete
permission to the authentication key myAuthKey
for uuid1
. Note that you must send UUID grants in separate requests than channel and channel group grants.
- Node.js
- Java
pubnub.grant(
{
uuids: ["uuid1"],
authKeys: ["myAuthKey"],
ttl: 1440, // 0 for infinite
get: true, // false to disallow
update: true, // false to disallow
delete: true // false to disallow
},
function (status) {
console.log(status);
}
);
pubnub.grant()
.uuids(Arrays.asList("uuid1")) // uuids to allow grant on
.authKeys(Arrays.asList("myAuthKey")) // the keys you are provisioning
.get(true) // allow those keys to get (false by default)
.update(true) // allow those keys to update (false by default)
.delete(true) // allow keys to delete (false by default)
.ttl(1440) // how long those keys will remain valid (0 for eternity)
.async(result -> { /* check result */ });
Revoke Permissions
To revoke permissions, use the grant
method with resource permissions set to false
. The ttl
parameter is not applicable and if a resource does not have a permission, it is ignored.
Wildcard revokes
You can revoke permissions from multiple channels using wildcards only if you previously granted permissions using the same wildcards. Wildcard revokes, similarly to grants, only work one level deep, like a.*
.
The request below revokes read
and write
permission from chats.room1
and chats.room2
channels and cg_user123
channel group:
- Node.js
- Java
- C#
- Python
- Go
pubnub.grant({
channels: ["chats.room1"],
channelGroups: ["cg_user123"]
authKeys: ["myAuthKey"],
read: false, // false to disallow
write: false, // false to disallow
}, (status) => {
// handle status
});
pubnub.grant()
.channels(Arrays.asList("chats.room1", "chats.room2"))
.channelGroups(Arrays.asList("cg_user123"))
.authKeys(Arrays.asList(authKey))
.write(false) // prevent those keys from writing
.read(false) // prevent those keys from reading the subscribed feed
.async(result -> { /* check result */ });
pubnub.Grant()
.Channels(new string[]{ "chats.room1", "chats.room2" })
.ChannelGroups(new string[]{ "cg_user123" })
.AuthKeys(new string[] { authKey })
.Write(false) // prevent those keys from writing
.Read(false) // prevent those keys from reading the subscribed feed
.Execute(new PNAccessManagerGrantResultExt(
(result, status) => {
// PNAccessManagerGrantResult is a parsed and abstracted response from server
}
));
pubnub.grant()\
.channels(["chats.room1", "chats.room2"])\
.channel_groups(["cg_user123"])\
.auth_keys([authKey])\
.read(False)\
.write(False)\
.sync()
res, status, err := pn.Grant()
.Channels([]string{"chats.room1", "chats.room2"})
.ChannelGroups([]string{"cg_user123"})
.AuthKeys([]string{authKey})
.Read(false)
.Write(false)
.Execute()
fmt.Println(res, status, err)
Client-Side Operations
Your login code may exist elsewhere in your app, but it's most commonly executed at app startup. If Access Manager is enabled, your clients are required to initialize the PubNub instance with an authKey
.
PubNub uses the provided authKey
to check for proper permissions before it allows the request to be executed. If the permissions exist for the requested operation on the channel, then the request is allowed to execute. If the proper permissions aren't found, the PubNub network responds with a 403 Forbidden
response.
- JavaScript
- Swift
- Objective-C
- Java
- C#
- Python
function login() {
// calls your server and returns the authKey
return authKey;
}
const authKey = login();
var pubnub = new PubNub({
publishKey: "myPublishKey",
subscribeKey: "mySubscribeKey",
uuid: "theClientUUID"
authKey: authKey
});
func login( ) -> String {
var authKey = ""
// calls your server and returns the authKey
return authKey;
}
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// more of your code here
let authKey = login()
var pnconfig = PubNubConfiguration(
publishKey: "myPublishKey",
subscribeKey: "mySubscribeKey"
show all 24 lines- (NSString *)login {
NSString *authKey = @"";
// calls your server and returns the authKey
return authKey;
}
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// more of your code here
NSString *authKey = [self login];
PNConfiguration *pnconfig = [PNConfiguration
configurationWithPublishKey:@"myPublishKey"
subscribeKey:@"mySubscribeKey"];
show all 23 linesprivate String login() {
String authKey = "";
// calls your server and returns the authKey
return authKey;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String authKey = login();
PNConfiguration pnconfig = new PNConfiguration();
pnconfig.setPublishKey("myPublishKey");
show all 21 linesprivate String Login() {
String authKey = "";
// calls your server and returns the authKey
return authKey;
}
static void Main()
{
String authKey = Login();
PNConfiguration pnconfig = new PNConfiguration();
pnconfig.PublishKey = "myPublishKey";
pnconfig.SubscribeKey = "mySubscribeKey";
pnconfig.Uuid = "theClientUUID";
pnconfig.AuthKey = authKey
show all 18 linesPython is typically used on a server where you would just initialize with the PubNub secret key. But if you have Python clients, you'll need to have them call your server that performs authentication to receive an auth key.
def login():
authKey = ""
# calls your server and returns the authKey
return authKey
authKey = login()
pnconfig = PNConfiguration()
pnconfig.publish_key = "my_publish_key"
pnconfig.subscribe_key = "my_subscribe_key"
pnconfig.uuid = "the_client_UUID"
pnconfig.auth_key = auth_key
pubnub = PubNub(pnconfig)
Your code in the callback function must use the status
and response
parameters to take necessary actions, whether it's to alert the client about the permission error, or to request the server to re-grant the permissions (on a new auth key), for example.