On this page

Access Manager v3 API for C# SDK

Access Manager isn't enabled by default
Without it, PubNub resources on this keyset have no access controls and clients can reach channels and metadata without permission checks — including Publish, Subscribe, and all other operations. Enable Access Manager in Admin Portal before deploying to production.

Access Manager lets you enforce security controls for client access to resources on the PubNub platform. With Access Manager v3, your servers (that use a PubNub instance configured with a secret key) can grant clients tokens with embedded permissions that provide access to individual PubNub resources:

  • For a limited time period.
  • Through resource lists or regular expression (RegEx) patterns.
  • In one API request, even when permissions differ (for example, read to channel1 and write to channel2).

You can add the authorizedUuid parameter to the grant request to restrict the token usage to one client with a given userId. Once specified, only this authorizedUuid will be able to use the token to make API requests for the specified resources, according to permissions given in the grant request.

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.

Request execution

Use try/catch when working with the C# SDK.

If a request has invalid parameters (for example, a missing required field), the SDK throws an exception. If the request reaches the server but fails (server error or network issue), the error details are available in the returned status.

1try
2{
3 PNResult<PNPublishResult> publishResponse = await pubnub.Publish()
4 .Message("Why do Java developers wear glasses? Because they can't C#.")
5 .Channel("my_channel")
6 .ExecuteAsync();
7
8 PNStatus status = publishResponse.Status;
9
10 Console.WriteLine("Server status code : " + status.StatusCode.ToString());
11}
12catch (Exception ex)
13{
14 Console.WriteLine($"Request can't be executed due to error: {ex.Message}");
15}

Grant token

Requires Access Manager add-on

This method requires that the Access Manager add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

Requires Secret Key authentication

Granting permissions to resources should be done by administrators whose SDK instance has been initialized with a Secret Key (available on the Admin Portal on your app's keyset).

The GrantToken() method generates a time-limited authorization token with an embedded access control list. The token defines time to live (TTL), AuthorizedUuid, and a set of permissions giving access to one or more resources:

  • Channels
  • ChannelGroups
  • Uuids (App Context UUID metadata, such as names or avatars)
  • Users (DataSync User objects)
  • DataSync (DataSync entities, relationships, and memberships)

Only this AuthorizedUuid will be able to use the token with the defined permissions. The authorized client will send the token to PubNub with each request until the token's TTL expires. Any unauthorized request or a request made with an invalid token will return a 403 with a respective error message.

The grant request allows your server to securely grant clients access to resources on the PubNub platform. Each resource type supports a specific set of operations:

ResourcePermissions
Channels
read, write, get, manage, update, join, delete
ChannelGroups
read, manage
Uuids
get, update, delete
Users
create, get, update, delete
DataSync (entities, relationships, memberships)
create, get, update, delete

For permissions and API operations mapping, refer to Manage Permissions with Access Manager v3.

DataSync user and channel objects are protected through the existing Users and Channels resource types, not through a separate DataSync scope. Uuids grants App Context metadata permissions and does not authorize DataSync user operations. Only DataSync entities, relationships, and memberships use the DataSync scope. Refer to DataSync access control for the full permission and resource-type mapping.

read, write, manage, and join stay messaging concepts and are not interpreted on Uuids, Users, or any DataSync resource.

danger
Don't mix Uuids with Users

Uuids and Users serialize to separate token scopes used by different products. The current C# grant builder nevertheless treats them as mutually exclusive across Resources and Patterns: supplying both can throw an ArgumentException or cause Users entries to be omitted with a warning. Use Uuids for App Context metadata grants and Users for DataSync user grants, in separate grant calls when you need both.

Method(s)

1pubnub.GrantToken()
2 .TTL(int)
3 .Meta(Dictionary<string, object>)
4 .AuthorizedUuid(string)
5 .Resources(PNTokenResources)
6 .Patterns(PNTokenPatterns)
7 .DataSyncProjections(PNDataSyncProjections)
8 .QueryParam(Dictionary<string, object>)
* required
ParameterDescription
TTL *
Type: int
Default:
n/a
Total number of minutes for which the token is valid.
  • The minimum allowed value is 1.
  • The maximum is 43,200 minutes (30 days).
AuthorizedUuid
Type: string
Default:
n/a
Single Uuid which is authorized to use the token to make API requests to PubNub.
Resources
Type: PNTokenResources
Default:
n/a
Object containing channel, channel group, UUID metadata, and DataSync permissions.
Patterns
Type: PNTokenPatterns
Default:
n/a
Object containing permissions to apply to all channel, channel group, UUID metadata, and DataSync resources matching the RegEx pattern.
Meta
Type: Dictionary<string, object>
Default:
n/a
Extra metadata to be published with the request. Values must be scalar only; arrays or objects aren't supported.
DataSyncProjections
Type: PNDataSyncProjections
Default:
n/a
Object assigning field-level projections to DataSync resources.
Execute
Type: PNCallback
Default:
n/a
PNCallback of type PNAccessManagerTokenResult.
ExecuteAsync
Type: None
Default:
n/a
Returns PNResult<PNAccessManagerTokenResult>.

PNTokenResources contains the following properties:

* required
ParameterDescription
Channels
Type: Dictionary<string, PNTokenAuthValues>
Default:
n/a
Dictionary object containing channel permissions.
ChannelGroups
Type: Dictionary<string, PNTokenAuthValues>
Default:
n/a
Dictionary object containing channel group permissions.
Uuids
Type: Dictionary<string, PNTokenAuthValues>
Default:
n/a
Dictionary object containing App Context UUID metadata permissions. Does not authorize DataSync users and cannot be combined with Users in one grant.
Users
Type: Dictionary<string, PNTokenAuthValues>
Default:
n/a
Dictionary object containing DataSync user permissions. Cannot be combined with Uuids in one grant.
DataSync
Type: PNDataSyncTokenScopes
Default:
n/a
Object containing DataSync resource permissions keyed by exact entity, relationship, or membership id.

PNTokenPatterns contains the following properties:

* required
ParameterDescription
Channels
Type: Dictionary<string, PNTokenAuthValues>
Default:
n/a
Dictionary object containing permissions to apply to all channels matching the RegEx pattern.
ChannelGroups
Type: Dictionary<string, PNTokenAuthValues>
Default:
n/a
Dictionary object containing permissions to apply to all channel groups matching the RegEx pattern.
Uuids
Type: Dictionary<string, PNTokenAuthValues>
Default:
n/a
Dictionary object containing App Context UUID metadata permissions for matching IDs. Does not authorize DataSync users and cannot be combined with Users in one grant.
Users
Type: Dictionary<string, PNTokenAuthValues>
Default:
n/a
Dictionary object containing DataSync user permissions for matching IDs. Cannot be combined with Uuids in one grant.
DataSync
Type: PNDataSyncTokenScopes
Default:
n/a
Object containing DataSync resource permissions to apply to all entities, relationships, or memberships matching the RegEx pattern.

PNDataSyncTokenScopes contains the following properties:

* required
ParameterDescription
Entities
Type: Dictionary<string, PNTokenAuthValues>
Default:
n/a
Dictionary object containing entity permissions keyed by exact id (Resources) or RegEx pattern (Patterns).
Relationships
Type: Dictionary<string, PNTokenAuthValues>
Default:
n/a
Dictionary object containing relationship permissions keyed by exact id (Resources) or RegEx pattern (Patterns).
Memberships
Type: Dictionary<string, PNTokenAuthValues>
Default:
n/a
Dictionary object containing membership permissions keyed by exact id (Resources) or RegEx pattern (Patterns).

PNTokenAuthValues contains the following properties:

Property NameTypeDescription
Read
bool
Read permission. Applies to Subscribe, History, and Presence.
Write
bool
Write permission. Applies to Publish.
Manage
bool
Manage permission. Applies to Channel Groups and App Context.
Create
bool
Create permission. Applies to DataSync.
Delete
bool
Delete permission. Applies to History, App Context, and DataSync.
Get
bool
Get permission. Applies to App Context and DataSync.
Update
bool
Update permission. Applies to App Context and DataSync.
Join
bool
Join permission. Applies to App Context.

For DataSync resources, only Create, Get, Update, and Delete are meaningful. Set only those four properties and leave Read, Write, Manage, and Join false (the default), the backend doesn't interpret them for DataSync resources.

PNDataSyncProjections contains the following properties:

* required
ParameterDescription
Resources
Type: PNDataSyncProjectionScope
Default:
n/a
Projection assignments for exact resource ids.
Patterns
Type: PNDataSyncProjectionScope
Default:
n/a
Projection assignments keyed by RegEx pattern.

PNDataSyncProjectionScope contains the following properties:

* required
ParameterDescription
Entities
Type: Dictionary<string, string>
Default:
n/a
id (or RegEx pattern) to projection name.
Users
Type: Dictionary<string, string>
Default:
n/a
id (or RegEx pattern) to projection name.
Channels
Type: Dictionary<string, string>
Default:
n/a
id (or RegEx pattern) to projection name.
Relationships
Type: Dictionary<string, string>
Default:
n/a
id (or RegEx pattern) to projection name.
Memberships
Type: Dictionary<string, string>
Default:
n/a
id (or RegEx pattern) to projection name.

Projections control which payload fields a token can read and write on a DataSync resource. Each id (or pattern) maps to one projection name, __default__ is the platform's built-in base projection, and exact id assignments (Resources) take priority over pattern matches (Patterns). A resource that matches neither falls back to __default__. The SDK passes any projection name through as an opaque string, __default__ isn't validated or defaulted client-side, it's a platform convention rather than an SDK-enforced value. A grant request that sets only DataSyncProjections, without any Resources or Patterns permissions, is still valid. Refer to the DataSync projections guide for how a token selects a projection.

A projection is declared per property on the class definition, so the names you can assign here are the ones the entity class or relationship class declares. A class allows at most 3 distinct projection names in total, and __default__ counts toward that 3 as soon as any property uses it, which leaves 2 custom names in practice.

note
PNDataSyncProjectionScope covers all five resource kinds

The platform accepts projection assignments for five DataSync resource kinds: entities, users, channels, relationships, and memberships. PNDataSyncProjectionScope exposes Entities, Users, Channels, Relationships, and Memberships, so you can assign a projection to a DataSync user or channel object the same way you would to an entity. Permission (not projection) for those same user and channel objects still comes from the top-level Users and Channels scopes. Uuids applies only to App Context metadata. DataSyncProjections only decides which fields of the object a token can read and write.

Projections also scope real-time event payloads, and each named projection publishes its view to a separate __<projection>__<id> channel. A token's projection assignment does not automatically select or authorize that event channel, so control who receives restricted fields with Channels grants on the projection channels. Refer to Projection channels.

Required key/value mappings

For a successful grant request, you must specify permissions for at least one UUID, channel, group, or DataSync resource, or a DataSyncProjections assignment, either as a resource list (Resources) or as a pattern (RegEx, Patterns).

Sample code

Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
1

Returns

The GrantToken() operation returns PNResult<PNAccessManagerTokenResult> which contains the following properties:

PropertyDescription
Result
Type: PNAccessManagerTokenResult
Returns a PNAccessManagerTokenResult object.
Status
Type: PNStatus
Returns a PNStatus object.

PNAccessManagerTokenResult contains the following properties:

* required
ParameterDescription
Token *
Type: String
Current token with embedded permissions.
1{ "Token":"p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI"}

Other examples

Grant an authorized client different levels of access to various resources in a single call

The code below grants my-authorized-uuid:

  • Read access to channel-a, channel-group-b, and get to uuid-c.
  • Read/write access to channel-b, channel-c, channel-d, and get/update to uuid-d.
1

Grant an authorized client read access to multiple channels using RegEx

The code below grants my-authorized-uuid read access to all channels that match the channel-[A-Za-z0-9] RegEx pattern.

1

Grant an authorized client different levels of access to various resources and read access to channels using RegEx in a single call

The code below grants the my-authorized-uuid:

  • Read access to channel-a, channel-group-b, and get to uuid-c.
  • Read/write access to channel-b, channel-c, channel-d, and get/update to uuid-d.
  • Read access to all channels that match the channel-[A-Za-z0-9] RegEx pattern.
1

Grant an authorized client access to DataSync resources

The code below grants user-alice get access to the entity product-sneaker-42 and get access to all entities that match the product-.* RegEx pattern.

1

Grant a token with a field-level projection

The code below grants user-alice the same access as above and assigns the public projection to the entity product-sneaker-42. With this projection, Alice reads and writes only the fields that the public projection exposes on that entity.

1

Error responses

If you submit an invalid request, the server returns HTTP 400 with a message that identifies the missing or incorrect argument. Causes can include a RegEx issue, an invalid timestamp, or incorrect permissions.

Revoke token

Requires Access Manager add-on

This method requires that the Access Manager add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

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.

The RevokeToken() method allows you to disable an existing token and revoke all permissions embedded within. You can only revoke a valid token previously obtained using the GrantToken() method.

Use this method for tokens with TTL less than or equal to 30 days. If you need to revoke a token with a longer TTL, contact support.

For more information, refer to Revoke permissions.

Method(s)

1pubnub.RevokeToken()
2 .Token(string)
3 .QueryParam(Dictionary<string, object>)
* required
ParameterDescription
Token *
Type: string
Default:
n/a
Existing token with embedded permissions.
Execute
Type: PNCallback
Default:
n/a
PNCallback of type PNAccessManagerRevokeTokenResult.
ExecuteAsync
Type: None
Default:
n/a
Returns PNResult<PNAccessManagerRevokeTokenResult>.

Sample code

1

Returns

The RevokeToken() operation returns PNResult<PNAccessManagerRevokeTokenResult> which contains the following properties:

PropertyDescription
Result
Type: PNAccessManagerRevokeTokenResult
Returns an empty PNAccessManagerRevokeTokenResult object when the token revocation request is successful.
Status
Type: PNStatus
Returns a PNStatus object for operations ending in success or failure.

Error Responses

If you submit an invalid request, the server returns an error status code with a descriptive message informing which of the provided arguments is missing or incorrect. Depending on the root cause, this operation may return the following errors:

  • 400 Bad Request
  • 403 Forbidden
  • 503 Service Unavailable

Parse token

The ParseToken() method decodes an existing token and returns the object containing permissions embedded in that token. The client can use this method for debugging to check the permissions to the resources or find out the token's TTL details.

If the token was granted with DataSync resource permissions, DataSync projections, or both, ParseToken() also decodes those into the returned object. Resources.DataSync and Patterns.DataSync (both of type PNDataSyncTokenScopes) expose the decoded entity, relationship, and membership permissions, and a new Projections property (type PNDataSyncProjections) exposes the decoded projection assignments. This lets you inspect DataSync grants directly for debugging.

Method(s)

1ParseToken(String token)
* required
ParameterDescription
token *
Type: String
Current token with embedded permissions.

Sample code

1

Returns

1

When the parsed token carries DataSync permissions or projections, the returned PNTokenContent also includes them. Resources.DataSync and Patterns.DataSync hold the same Entities, Relationships, and Memberships dictionaries described under Grant token, and Projections holds the same Resources/Patterns projection scopes accepted by .DataSyncProjections(). For example, a token granted with the product-sneaker-42 entity permission and the public projection from that entity parses to a Resources.DataSync.Entities entry for product-sneaker-42 and a Projections.Resources.Entities entry mapping product-sneaker-42 to "public".

Error Responses

If you receive an error while parsing the token, it may suggest that the token is damaged. In that case, request the server to issue a new one.

Set token

The SetAuthToken() method is used by the client devices to update the authentication token granted by the server.

Method(s)

1SetAuthToken(String token)
* required
ParameterDescription
token *
Type: String
Current token with embedded permissions.

Sample code

1

Returns

This method doesn't return any response value.

Grant token - spaces & users (deprecated)

Deprecated

This method is deprecated and will be removed in a future version. Please use the grantToken() method instead.

Requires Access Manager add-on

This method requires that the Access Manager add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

The GrantToken() method generates a time-limited authorization token with an embedded access control list. The token defines time to live (TTL), AuthorizedUserId, and a set of permissions giving access to one or more resources:

  • Spaces
  • Users (other users' metadata, such as their names or avatars)

Only this AuthorizedUserId will be able to use the token with the defined permissions. The authorized client will send the token to PubNub with each request until the token's TTL expires. Any unauthorized request or a request made with an invalid token will return a 403 with a respective error message.

Permissions - spaces & users (deprecated)

The grant request allows your server to securely grant your clients access to the resources within the PubNub Platform. There is a limited set of operations the clients can perform on every resource:

ResourcePermissions
Spaces
read, write, get, manage, update, join, delete
Users
get, update, delete

For permissions and API operations mapping, refer to Manage Permissions with Access Manager v3.

TTL - spaces & users (deprecated)

The TTL (time to live) parameter is the number of minutes before the granted permissions expire. The client will require a new token to be granted before expiration to ensure continued access. ttl is a required parameter for every grant call and there is no default value set for it. The max value for ttl is 43,200 (30 days).

For more details, see TTL in Access Manager v3.

RegEx - spaces & users (deprecated)

Use regular expressions (RegEx) to set permissions by pattern instead of listing every resource. Set RegEx permissions as Patterns before making a grant request.

For more details, see RegEx in Access Manager v3.

Authorized user ID - spaces & users (deprecated)

Setting an AuthorizedUserId in the token specifies which client should use this token in every request to PubNub. If you do not set AuthorizedUserId during the grant request, the token can be used by any client with any UserId. Restrict tokens to a single AuthorizedUserId to prevent impersonation.

For more details, see Authorized UUID in Access Manager v3.

Method(s) - spaces & users (deprecated)

1pubnub.GrantToken()
2 .TTL(int)
3 .Meta(Dictionary<string, object>)
4 .AuthorizedUserId(string)
5 .Resources(PNTokenResources)
6 .Patterns(PNTokenPatterns)
7 .QueryParam(Dictionary<string, object>)
* required
ParameterDescription
TTL *
Type: int
Default:
n/a
Total number of minutes for which the token is valid.
  • The minimum allowed value is 1.
  • The maximum is 43,200 minutes (30 days).
AuthorizedUserId
Type: string
Default:
n/a
Single Uuid which is authorized to use the token to make API requests to PubNub.
Resources
Type: PNTokenResources
Default:
n/a
Object containing channel, channel group, and UUID metadata permissions.
Patterns
Type: PNTokenPatterns
Default:
n/a
Object containing permissions to apply to all channel, channel group, and UUID metadata matching the RegEx pattern.
Meta
Type: Dictionary<string, object>
Default:
n/a
Extra metadata to be published with the request. Values must be scalar only; arrays or objects aren't supported.
Execute
Type: PNCallback
Default:
n/a
PNCallback of type PNAccessManagerTokenResult.
ExecuteAsync
Type: None
Default:
n/a
Returns PNResult<PNAccessManagerTokenResult>.

PNTokenResources contains the following properties:

* required
ParameterDescription
Spaces
Type: Dictionary<string, PNTokenAuthValues>
Default:
n/a
Dictionary object containing Space permissions.
Users
Type: Dictionary<string, PNTokenAuthValues>
Default:
n/a
Dictionary object containing User metadata permissions.

PNTokenPatterns contains the following properties:

* required
ParameterDescription
Spaces
Type: Dictionary<string, PNTokenAuthValues>
Default:
n/a
Dictionary object containing permissions to apply to all Spaces matching the RegEx pattern.
Users
Type: Dictionary<string, PNTokenAuthValues>
Default:
n/a
Dictionary object containing permissions to apply to all User metadata matching the RegEx pattern.

PNTokenAuthValues contains the following properties:

Property NameTypeDescription
Read
bool
Read permission.
Write
bool
Write permission.
Manage
bool
Manage permission.
Delete
bool
Delete permission.
Get
bool
Get permission.
Update
bool
Update permission.
Join
bool
Join permission.
Required key/value mappings

For a successful grant request, you must specify permissions for at least one User or Space either as a resource list or as a pattern (RegEx).

Sample code - spaces & users (deprecated)

1

Returns - spaces & users (deprecated)

The GrantToken() operation returns PNResult<PNAccessManagerTokenResult> which contains the following properties:

PropertyDescription
Result
Type: PNAccessManagerTokenResult
Returns a PNAccessManagerTokenResult object.
Status
Type: PNStatus
Returns a PNStatus object.

PNAccessManagerTokenResult contains the following properties:

* required
ParameterDescription
Token *
Type: String
Current token with embedded permissions.
1{ "Token":"p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI"}

Other examples - spaces & users (deprecated)

Grant an authorized client different levels of access to various resources in a single call - spaces & users (deprecated)

The code below grants my-authorized-userId:

  • Read access to space-a, and get to userId-c.
  • Read/write access to space-b, space-c, space-d, and get/update to userId-d.
1

Grant an authorized client read access to multiple spaces using RegEx - spaces & users (deprecated)

The code below grants my-authorized-userId read access to all channels that match the space-[A-Za-z0-9] RegEx pattern.

1

Grant an authorized client different levels of access to various resources and read access to spaces using RegEx in a single call - spaces & users (deprecated)

The code below grants the my-authorized-userId:

  • Read access to space-a and userId-c.
  • Read/write access to space-b, space-c, space-d, and get/update to userId-d.
  • Read access to all channels that match the space-[A-Za-z0-9] RegEx pattern.
1

Error responses - spaces & users (deprecated)

If you submit an invalid request, the server returns HTTP 400 with a message that identifies the missing or incorrect argument. Causes can include a RegEx issue, an invalid timestamp, or incorrect permissions.