Access Manager v3 API for C# SDK
Access Manager isn't enabled by default
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,
readtochannel1andwritetochannel2).
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:
ChannelsChannelGroupsUuids(App Context UUID metadata, such as names or avatars)Users(DataSyncUserobjects)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.
- Permissions
- TTL (time to live)
- RegEx patterns
- Authorized UUID
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:
| Resource | Permissions |
|---|---|
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
Uuids with UsersUuids 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.
The ttl (time to live) parameter defines how many minutes the permissions remain valid. After expiration, the client must get a new token to maintain access. ttl is required for every grant call. There is no default value. The maximum value is 43,200 (30 days).
For more details, see TTL in Access Manager v3.
Use regular expression (RegEx) patterns to set permissions without listing each resource. Define RegEx permissions for a given resource type in the grant request. Patterns are evaluated on the server using RE2-style syntax; backreferences and lookaround assertions are not supported.
For more details, see RegEx in Access Manager v3.
Setting an AuthorizedUuid in the token specifies which client should use this token in every request to PubNub. If you do not set AuthorizedUuid during the grant request, the token can be used by any client with any UUID. Restrict tokens to a single AuthorizedUuid to prevent impersonation.
For more details, see Authorized UUID in Access Manager v3.
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>)
| Parameter | Description |
|---|---|
TTL *Type: intDefault: n/a | Total number of minutes for which the token is valid.
|
AuthorizedUuidType: stringDefault: n/a | Single Uuid which is authorized to use the token to make API requests to PubNub. |
ResourcesType: PNTokenResourcesDefault: n/a | Object containing channel, channel group, UUID metadata, and DataSync permissions. |
PatternsType: PNTokenPatternsDefault: n/a | Object containing permissions to apply to all channel, channel group, UUID metadata, and DataSync resources matching the RegEx pattern. |
MetaType: 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. |
DataSyncProjectionsType: PNDataSyncProjectionsDefault: n/a | Object assigning field-level projections to DataSync resources. |
ExecuteType: PNCallbackDefault: n/a | PNCallback of type PNAccessManagerTokenResult. |
ExecuteAsyncType: None Default: n/a | Returns PNResult<PNAccessManagerTokenResult>. |
PNTokenResources contains the following properties:
| Parameter | Description |
|---|---|
ChannelsType: Dictionary<string, PNTokenAuthValues>Default: n/a | Dictionary object containing channel permissions. |
ChannelGroupsType: Dictionary<string, PNTokenAuthValues>Default: n/a | Dictionary object containing channel group permissions. |
UuidsType: 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. |
UsersType: Dictionary<string, PNTokenAuthValues>Default: n/a | Dictionary object containing DataSync user permissions. Cannot be combined with Uuids in one grant. |
DataSyncType: PNDataSyncTokenScopesDefault: n/a | Object containing DataSync resource permissions keyed by exact entity, relationship, or membership id. |
PNTokenPatterns contains the following properties:
| Parameter | Description |
|---|---|
ChannelsType: Dictionary<string, PNTokenAuthValues>Default: n/a | Dictionary object containing permissions to apply to all channels matching the RegEx pattern. |
ChannelGroupsType: Dictionary<string, PNTokenAuthValues>Default: n/a | Dictionary object containing permissions to apply to all channel groups matching the RegEx pattern. |
UuidsType: 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. |
UsersType: Dictionary<string, PNTokenAuthValues>Default: n/a | Dictionary object containing DataSync user permissions for matching IDs. Cannot be combined with Uuids in one grant. |
DataSyncType: PNDataSyncTokenScopesDefault: n/a | Object containing DataSync resource permissions to apply to all entities, relationships, or memberships matching the RegEx pattern. |
PNDataSyncTokenScopes contains the following properties:
| Parameter | Description |
|---|---|
EntitiesType: Dictionary<string, PNTokenAuthValues>Default: n/a | Dictionary object containing entity permissions keyed by exact id (Resources) or RegEx pattern (Patterns). |
RelationshipsType: Dictionary<string, PNTokenAuthValues>Default: n/a | Dictionary object containing relationship permissions keyed by exact id (Resources) or RegEx pattern (Patterns). |
MembershipsType: 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 Name | Type | Description |
|---|---|---|
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:
| Parameter | Description |
|---|---|
ResourcesType: PNDataSyncProjectionScopeDefault: n/a | Projection assignments for exact resource ids. |
PatternsType: PNDataSyncProjectionScopeDefault: n/a | Projection assignments keyed by RegEx pattern. |
PNDataSyncProjectionScope contains the following properties:
| Parameter | Description |
|---|---|
EntitiesType: Dictionary<string, string>Default: n/a | id (or RegEx pattern) to projection name. |
UsersType: Dictionary<string, string>Default: n/a | id (or RegEx pattern) to projection name. |
ChannelsType: Dictionary<string, string>Default: n/a | id (or RegEx pattern) to projection name. |
RelationshipsType: Dictionary<string, string>Default: n/a | id (or RegEx pattern) to projection name. |
MembershipsType: 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 kindsThe 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
1
Returns
The GrantToken() operation returns PNResult<PNAccessManagerTokenResult> which contains the following properties:
| Property | Description |
|---|---|
ResultType: PNAccessManagerTokenResult | Returns a PNAccessManagerTokenResult object. |
StatusType: PNStatus | Returns a PNStatus object. |
PNAccessManagerTokenResult contains the following properties:
| Parameter | Description |
|---|---|
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 touuid-c. - Read/write access to
channel-b,channel-c,channel-d, and get/update touuid-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 touuid-c. - Read/write access to
channel-b,channel-c,channel-d, and get/update touuid-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>)
| Parameter | Description |
|---|---|
Token *Type: stringDefault: n/a | Existing token with embedded permissions. |
ExecuteType: PNCallbackDefault: n/a | PNCallback of type PNAccessManagerRevokeTokenResult. |
ExecuteAsyncType: None Default: n/a | Returns PNResult<PNAccessManagerRevokeTokenResult>. |
Sample code
1
Returns
The RevokeToken() operation returns PNResult<PNAccessManagerRevokeTokenResult> which contains the following properties:
| Property | Description |
|---|---|
ResultType: PNAccessManagerRevokeTokenResult | Returns an empty PNAccessManagerRevokeTokenResult object when the token revocation request is successful. |
StatusType: 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 Request403 Forbidden503 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)
| Parameter | Description |
|---|---|
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)
| Parameter | Description |
|---|---|
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:
SpacesUsers(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:
| Resource | Permissions |
|---|---|
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>)
| Parameter | Description |
|---|---|
TTL *Type: intDefault: n/a | Total number of minutes for which the token is valid.
|
AuthorizedUserIdType: stringDefault: n/a | Single Uuid which is authorized to use the token to make API requests to PubNub. |
ResourcesType: PNTokenResourcesDefault: n/a | Object containing channel, channel group, and UUID metadata permissions. |
PatternsType: PNTokenPatternsDefault: n/a | Object containing permissions to apply to all channel, channel group, and UUID metadata matching the RegEx pattern. |
MetaType: 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. |
ExecuteType: PNCallbackDefault: n/a | PNCallback of type PNAccessManagerTokenResult. |
ExecuteAsyncType: None Default: n/a | Returns PNResult<PNAccessManagerTokenResult>. |
PNTokenResources contains the following properties:
| Parameter | Description |
|---|---|
SpacesType: Dictionary<string, PNTokenAuthValues>Default: n/a | Dictionary object containing Space permissions. |
UsersType: Dictionary<string, PNTokenAuthValues>Default: n/a | Dictionary object containing User metadata permissions. |
PNTokenPatterns contains the following properties:
| Parameter | Description |
|---|---|
SpacesType: Dictionary<string, PNTokenAuthValues>Default: n/a | Dictionary object containing permissions to apply to all Spaces matching the RegEx pattern. |
UsersType: 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 Name | Type | Description |
|---|---|---|
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:
| Property | Description |
|---|---|
ResultType: PNAccessManagerTokenResult | Returns a PNAccessManagerTokenResult object. |
StatusType: PNStatus | Returns a PNStatus object. |
PNAccessManagerTokenResult contains the following properties:
| Parameter | Description |
|---|---|
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 touserId-c. - Read/write access to
space-b,space-c,space-d, and get/update touserId-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-aanduserId-c. - Read/write access to
space-b,space-c,space-d, and get/update touserId-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.