Access Manager v2 API for PubNub C# SDK
PubNub Access Manager (PAM) extends PubNub's existing security framework by allowing developers to create and enforce secure access to channels and channel groups throughout the PubNub Real-Time Network.
As soon as Access Manager is enabled, no pub/sub-operations can be done without first explicitly providing an authorization token to the PubNub object. If an invalid token is provided, the requesting client will receive a Forbidden Error.
Learn more about Access Manager here.
Grant
Requires Access Manager add-onRequires that the Access Manager add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-
Description
This function establishes access permissions for PubNub Access Manager (PAM) by setting the read
or write
attribute to true
. A grant
with read
or write
set to false
(or not included) will revoke any previous grants with read
or write
set to true
. Permissions can be applied to any one of three levels:
- Application level privileges are based on
SubscribeKey
applying to all associated channels. - Channel level privileges are based on a combination of
SubscribeKey
andchannel
name. - User level privileges are based on the combination of
SubscribeKey
,channel
andAuthKeys
.
Warning
For NTP synchronization, please ensure that you have configured NTP on your server to keep the clock in sync. This is to prevent system clock drift leading to 400 Invalid Timestamp
error response.
Wildcard notation allows you to grant permissions to multiple channels at a time and later revoke these permissions in the same manner. You can only 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.
Wildcard revokes
You can revoke permissions with wildcards from one level deep, like a.*
, only when you initially used wildcards to grant permissions to a.*
.
When a user attempts to access a PubNub resource, PAM will evaluate any existing rules using the following order of precedence before access to a channel is granted to the user:
Application Level - PAM privileges are always evaluated first at the Application level. If either
read
orwrite
attribute is set totrue
for aSubscribeKey
, PAM will immediately grant access for that attribute without proceeding to check permissions at eitherChannel
orUser
levels. If an attribute is set tofalse
at the Application level, PAM proceeds to evaluate the attribute at the next most granular level.Use application level grants with caution
When access is granted on an application level,
all channels and users
will have access.Application level grants can also happen due to a bug in your code. For example, Null parameters for channels and auth-keys can cause accidental application level grants.
Channel Level - After first verifying an attribute at the Application level, PAM evaluates the attribute at the Channel level. If an attribute is set to
true
for a combination ofSubscribeKey
andchannel
, PAM grants access for that attribute at theChannel
level without proceeding to check whether there may beuser
level permissions.User Level - As a final step PAM evaluates the attributes at the
User
level. If an attribute is set totrue
forSubscribeKey
,channel
andAuthKeys
, access is granted for that attribute.
Note
If an argument of the grant
is not provided, an expected default will be assumed.
read
andwrite
arguments default tofalse
- no
AuthKeys
results inchannel-level
grant - no
channel
results inapplication-level
grant
No Permissions - If no permissions were granted at any of the three levels, the user will be denied access to the PubNub resource and receive a 403 error message. This is the default behavior for a PAM enabled application.
Important
Note that privileges specifically granted to an application's SubscribeKey
always take precedence over privileges granted to channel
or AuthKeys
. Therefore an application that requires authentication at the user
level should not grant access at either the Application
or Channel
levels.
- History To access historical messages you must grant full
read
access at either theSubscribeKey
orchannel
level. Note that you must grantread
access to each channel in a channel group individually. When a user has the appropriate permissions they can access any data stored. If they do not have access a403
will be returned by PAM. - Presence To grant access to Presence for a particular channel name you must also allow
read
andwrite
access to the presencechannel
name which is specified by adding the-pnpres
suffix to the name. Also note that aleave
will fail in the case where a user's grant expires while connected. An HTTP403
will be returned. - APNS Standard permissions are required for publishing.
The duration of permission set with Grant()
are controlled by setting a time-to-live(TTL
). If a TTL
is not specified it is automatically set to 1440
minutes by default. Once the TTL
associated with an entry in PAM has expired, the read
and write
attributes are immediately set to false
for that entry in the PAM table.
Caution
PAM grant or revoke requests must be less than ~32KB at a time, or the client will return an error. For requests greater than 32KB, break them into smaller batched requests.
Warning
When the message size exceeds 32KB the server returns the HTTP Error code 500, instead of the correct error code 414.
Note
The limit on the total amount of channels
that you can pass at once when using Grant()
is 200
.
Method(s)
To Grant Permissions on a Channel
you can use the following method(s) in the C# V4 SDK:
pubnub.Grant().Uuids(Array).Channels(Array).ChannelGroups(Array).AuthKeys(Array).Get(bool).Update(bool).Join(bool).Write(bool).Read(bool).Delete(bool).Manage(bool).TTL(long).QueryParam(Dictionary<string,object>)
Parameter Type Required Description Uuids
Array Optional Specifies a list of uuids
on which togrant
permissions. You can't grant permissions to channels and channel groups in the same request if you decide to useuuids
.
This parameter does not support wildcards.Channels
Array Optional Specifies the channels
on which togrant
permissions. If nochannels/channelGroups
are specified, then thegrant
applies to any and allchannels/channelGroups
that have been or will be created for thatpublish/subscribe
key set. Furthermore, any existing or future grants on specificchannels
are ignored, until theall channels
grant is revoked. It is possible togrant
permissions to multiplechannels
simultaneously.Wildcard notation likea.*
can be used togrant
access on channels. You cangrant
one level deep.a.*
- you can grant on this.*
anda.b.*
- grant will not work on these levels. If you grant on*
ora.b.*
, the grant will treat*
ora.b.*
as a single channel named either*
ora.b.*
.
ChannelGroups
Array Optional Specifies the channelGroups
togrant
permissions. If nochannels/channelGroups
are specified, then thegrant
applies to any and allchannels/channelGroups
that have been or will be created for thatpublish/subscribe
key set. Furthermore, any existing or future grants on specificchannelGroups
are ignored, until theall channelGroups
grant is revoked. It is possible togrant
permissions to multiplechannelGroups
simultaneously.
This parameter does not support wildcards.AuthKeys
Array Optional Specifies auth
Key to grant permissions. It is possible to specify multipleauth
keys. You can also grant access to a singleauth
key for multiplechannels
at the same time. Zero or morechannels
with zero or moreauth
tokens are allowed.Get
bool Optional Get
permission.Update
bool Optional Update
permission.Join
bool Optional Join
permission.Write
bool Optional Write
permission.Read
bool Optional Read
permission.Delete
bool Optional Delete
permission.Manage
bool Optional Manage
permission.TTL
long Optional Time to live
for permission to be validQueryParam
Dictionary<string, object> Optional Dictionary object
to pass name/value pairs as querystring
params with PubNub URL request for debug purpose.Async
PNCallback Deprecated PNCallback
of typePNAccessManagerGrantResult
Execute
PNCallback Yes PNCallback
of typePNAccessManagerGrantResult
ExecuteAsync
None Optional Returns PNResult<PNAccessManagerGrantResult>
.
Basic Usage
Grant PAM Permissions for channel and AuthKeys
PNResult<PNAccessManagerGrantResult> grantResponse = await pubnub.Grant()
.Channels(new string[]{
//channels to allow grant on
"ch1",
"ch2",
"ch3"
})
.ChannelGroups(new string[] {
// groups to allow grant on
"cg1",
"cg2",
"cg3"
})
.AuthKeys(new string[] {
// the keys we are provisioning
"key1",
"key2",
"key3"
})
.Write(true) // allow those keys to write (false by default)
.Manage(true) // allow those keys to manage channel groups (false by default)
.Read(true) // allow keys to read the subscribe feed (false by default)
.Delete(true) // allow those keys to delete the subscribe feed (false by default)
.TTL(12337) // how long those keys will remain valid (0 for eternity)
.ExecuteAsync();
PNAccessManagerGrantResult grantResult = grantResponse.Result;
PNStatus status = grantResponse.Status;
// PNAccessManagerGrantResult is a parsed and abstracted response from server
Returns
The Grant()
operation returns a PNResult<PNAccessManagerGrantResult>
which contains the following properties:
Property Name | Type | Description |
---|---|---|
Result | PNAccessManagerGrantResult | Returns a PNAccessManagerGrantResult object. |
Status | PNStatus | Returns a PNStatus object. |
PNAccessManagerGrantResult
contains the following properties:
Property Name | Type | Description |
---|---|---|
Level | string | Subkey or channel level. |
Ttl | int | Ttl of grant . |
SubscribeKey | string | The SubscribeKey . |
Channels | Dictionary<string, Dictionary<string, PNAccessManagerKeyData>> | Access rights per channel . See PNAccessManagerKeyData for more details. |
ChannelGroups | Dictionary<string, Dictionary<string, PNAccessManagerKeyData>> | Access rights per channel group . See PNAccessManagerKeyData for more details. |
PNAccessManagerKeyData
Property Name | Type | Description |
---|---|---|
ReadEnabled | bool | true if the user has read rights. |
WriteEnabled | bool | true if the user has write rights. |
DeleteEnabled | bool | true if the user has delete rights. |
ManageEnabled | bool | true if the user has manage rights. |
Other Examples
Grant PAM Permissions for channel and AuthKeys synchronously:
pubnub.Grant() .Channels(new string[]{ //channels to allow grant on "ch1", "ch2", "ch3" }) .ChannelGroups(new string[] { // groups to allow grant on "cg1", "cg2", "cg3" }) .AuthKeys(new string[] { // the keys we are provisioning "key1", "key2", "key3" }) .Write(true) // allow those keys to write (false by default) .Manage(true) // allow those keys to manage channel groups (false by default) .Read(true) // allow keys to read the subscribe feed (false by default) .Delete(true) // allow those keys to delete the subscribe feed (false by default) .TTL(12337) // how long those keys will remain valid (0 for eternity) .Execute(new PNAccessManagerGrantResultExt( (result, status) => { // PNAccessManagerGrantResult is a parsed and abstracted response from server } ));
Grant subscribe access to a channel only for clients with a specific AuthKeys with a 5 minute ttl:
PNResult<PNAccessManagerGrantResult> grantResponse = await pubnub.Grant() .Channels(new string[] { "my_channel" }) .Write(false) .Read(true) .Delete(false) .AuthKeys(new string[] { "my_ro_authkey" }) .TTL(5) .ExecuteAsync(); PNAccessManagerGrantResult grantResult = grantResponse.Result; PNStatus status = grantResponse.Status; // PNAccessManagerGrantResult is a parsed and abstracted response from server
The above code would return the following response to the client:
{ "status" : 200, "message" : "Success", "payload" : { "ttl" : 5, "auths" : { "my_ro_authkey" : { "r" : 1, "w" : 0, "d" : 0 } }, "subscribe_key" : "my_subkey", "level" : "user", "channel" : "my_channel" }, "service" : "Access Manager" }
Allow access to a specific channel for Presence:
PNResult<PNAccessManagerGrantResult> grantResponse = await pubnub.Grant() .Channels(new string[] { "my_channel-pnpres" }) .Write(true) .Read(true) .Delete(true) .ExecuteAsync(); PNAccessManagerGrantResult grantResult = grantResponse.Result; PNStatus status = grantResponse.Status; // PNAccessManagerGrantResult is a parsed and abstracted response from server
Grant PAM Permissions for channel group:
PNResult<PNAccessManagerGrantResult> grantResponse = await pubnub.Grant() .ChannelGroups(new string[] { "cg1", "cg2", "cg3" }) .AuthKeys(new string[] { "key1", "key2", "key3" }) .Write(true) .Manage(true) .Read(true) .Delete(true) .TTL(12337) .ExecuteAsync(); PNAccessManagerGrantResult grantResult = grantResponse.Result; PNStatus status = grantResponse.Status; // PNAccessManagerGrantResult is a parsed and abstracted response from server
The above code would return the following response to the client:
{ "status":200, "message":"Success", "payload":{ "ttl":5, "auths":{ "my_rw_authkey":{ "r":1, "w":1, "d":1 } }, "subscribe_key":"my_subkey", "level":"user", "channel":"my_channel" }, "service":"Access Manager" }
Grant get, update, and delete access to a uuid only for clients with a specific AuthKeys with a 24 hrs ttl:
PNResult<pnaccessmanagergrantresult> grantResponse = await pubnub.Grant() .Uuids(new string[] { "my_uuid" }) .Get(true) .Update(true) .Delete(true) .AuthKeys(new string[] { "my_ro_authkey" }) .TTL(1440) .ExecuteAsync(); PNAccessManagerGrantResult grantResult = grantResponse.Result; PNStatus status = grantResponse.Status; // PNAccessManagerGrantResult is a parsed and abstracted response from server </pnaccessmanagergrantresult>
-
Use application level grants with caution
When access is granted on an application level,
all channels and users
will have access.Application level grants can also happen due to a bug in your code. For example, Null parameters for channels and auth-keys can cause accidental application level grants.
PNResult<PNAccessManagerGrantResult> grantResponse = await pubnub.Grant() .Write(true) .Read(true) .Delete(true) .ExecuteAsync(); PNAccessManagerGrantResult grantResult = grantResponse.Result; PNStatus status = grantResponse.Status; // PNAccessManagerGrantResult is a parsed and abstracted response from server
-
PNResult<PNAccessManagerGrantResult> grantResponse = await pubnub.Grant() .Channels(new string[] { "my_channel" }) .Write(true) .Read(true) .Delete(true) .ExecuteAsync(); PNAccessManagerGrantResult grantResult = grantResponse.Result; PNStatus status = grantResponse.Status; // PNAccessManagerGrantResult is a parsed and abstracted response from server
-
PNResult<PNAccessManagerGrantResult> grantResponse = await pubnub.Grant() .Channels(new string[] { "my_channel" }) .Write(true) .Read(true) .Delete(true) .AuthKeys(new string[]{ "my_authkey" }) .TTL(5) .ExecuteAsync(); PNAccessManagerGrantResult grantResult = grantResponse.Result; PNStatus status = grantResponse.Status; // PNAccessManagerGrantResult is a parsed and abstracted response from server