Access Manager v2 API for Python-Asyncio SDK

Deprecated

The grant() and audit() methods of Access Manager v2 are deprecated in the Python-Asyncio SDK. Calling them emits a DeprecationWarning. Use grant_token() instead.

Access Manager 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.

Once Access Manager is enabled, no publish or subscribe operation works until you give the PubNub object an authorization token. If the token is invalid, the client receives a Forbidden error.

To learn more about Access Manager, see Managing Permissions with Access Manager.

A builder sends its request when you await its future(). A request that fails, or fails validation, does not raise an exception. future() resolves with a PubNubAsyncioException whose result is None and whose status holds the error. Call is_error() on the awaited value before you read result.

Grant​

Requires Access Manager add-on

This method requires that the Access Manager add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.

The grant() method allows you to grant permissions for one or more resources to one or more auth_keys. You may need to make multiple grant calls with an auth key so that you can specify permissions for each channel, channel group, and uuid resource. For common permissions, a single request is usually enough.

Privileges granted to an application's subscribe key always take precedence over privileges granted to a channel or an auth key. An application that requires authentication at the user level must not grant access at the Application or Channel levels. See Grant levels.

grant() requires the subscribe key, the publish key, and the secret key. A missing key makes future() resolve with a PubNubAsyncioException with the message Subscribe key not configured, Publish key not configured, or Secret key is not configured.

Permissions​

A grant request lets your server give clients access to the following resources. Each resource supports a limited set of permissions that control which operations clients can run. For the mapping of permissions to API operations, see Managing Permissions with Access Manager.

ResourcePermissions
channelread, write, get, manage, update, join, delete
uuidget, update, delete
channel_groupread, manage
category (channels, uuids)get only

In grant(), categories() selects the channels and uuids categories.

  • A category permission lets a token list all metadata of one resource type on your subscribe key. Valid categories are channels and uuids. The only permission is get (32).
  • A get permission on one named channel or user, or on a pattern, does not grant a category.
  • A token can contain only categories. It needs no resource or pattern.
  • When enumeration enforcement is enabled for a keyset, App Context list requests from a token or auth key without the matching category permission return a 403 error.

Wildcard permissions​

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 with a..
  • * or a.b.* won't work this way. If you grant on * or a.b.*, the grant treats * or a.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 used wildcards to grant permissions to a.*.

Grant levels​

When a user attempts to access a PubNub resource, Access Manager evaluates the existing rules in this order of precedence before it grants access to a channel:

  1. Application Level - Access Manager privileges are always evaluated first at the Application level. If the read or write attribute is True for a subscribe key, Access Manager grants access for that attribute immediately and doesn't check the Channel or User levels. If an attribute is False at the Application level, Access Manager proceeds to evaluate the attribute at the next most granular level.
  2. Channel Level - After first verifying an attribute at the Application level, Access Manager evaluates the attribute at the Channel level. If an attribute is True for a combination of subscribe key and channel, Access Manager grants access for that attribute at the Channel level and doesn't check the User level.
  3. User Level (Recommended) - As a final step, Access Manager evaluates the attributes at the User level. If an attribute is True for the subscribe key, channel, and auth key, Access Manager grants access for that attribute. User level grants can also give an auth key access to channel groups and uuids. They require auth keys and are the recommended way to manage permissions for individual users. Assign each user a unique auth key and pass it to them securely.

Method(s)​

To Grant Permissions on a Channel, you can use the following method(s) in the Python-Asyncio SDK:

1await pubnub.grant() \
2 .auth_keys(auth_keys: Union[str, List[str]]) \
3 .channels(channels: Union[str, List[str]]) \
4 .channel_groups(channel_groups: Union[str, List[str]]) \
5 .uuids(uuids: Union[str, List[str]]) \
6 .categories(categories: List[str]) \
7 .read(read: bool) \
8 .write(write: bool) \
9 .manage(manage: bool) \
10 .delete(delete: bool) \
11 .get(get: bool) \
12 .update(update: bool) \
13 .join(join: bool) \
14 .ttl(ttl: int) \
15 .future() -> AsyncioEnvelope
auth_keys#
Type: Union[str, List[str]]
Default: no default
Auth keys to grant permissions to. Pass several keys as a list or as a comma-separated string. Auth keys are required for user-level grants, for uuids, and for categories. Without them, the permissions apply to all clients on channel level or application level. See Grant levels.
channels#
Type: Union[str, List[str]]
Default: no default
Channels on which to grant permissions. Pass several channels as a list or as a comma-separated string. This parameter supports wildcards that are one level deep (a.*).
channel_groups#
Type: Union[str, List[str]]
Default: no default
Channel groups on which to grant permissions. This parameter does not support wildcards.
uuids#
Type: Union[str, List[str]]
Default: no default
Uuids on which to grant permissions. Requires auth_keys. You can't grant permissions to channels or channel groups in the same request if you decide to use uuids. This parameter does not support wildcards.
categories#
Type: List[str]
Default: no default
Categories to grant. Valid values are channels, which lists all channel metadata, and uuids, which lists all uuid metadata. A get permission on a named channel or uuid doesn't imply this. Requires auth_keys. Refer to Category permissions.
read#
Type: bool
Default: no default
Pass True to grant read permissions or False to remove them. If you don't call the method, the SDK doesn't send the flag, and any other value counts as False.
write#
Type: bool
Default: no default
Pass True to grant write permissions or False to remove them. If you don't call the method, the SDK doesn't send the flag, and any other value counts as False.
manage#
Type: bool
Default: no default
Pass True to grant manage permissions or False to remove them. If you don't call the method, the SDK doesn't send the flag, and any other value counts as False.
delete#
Type: bool
Default: no default
Pass True to grant delete permissions or False to remove them. If you don't call the method, the SDK doesn't send the flag, and any other value counts as False.
get#
Type: bool
Default: no default
Pass True to grant get permissions or False to remove them. If you don't call the method, the SDK doesn't send the flag, and any other value counts as False.
update#
Type: bool
Default: no default
Pass True to grant update permissions or False to remove them. If you don't call the method, the SDK doesn't send the flag, and any other value counts as False.
join#
Type: bool
Default: no default
Pass True to grant join permissions or False to remove them. If you don't call the method, the SDK doesn't send the flag, and any other value counts as False.
ttl#
Type: int
Default: no default
Time in minutes for which the granted permissions are valid. If you omit it, the service applies 1440 (24 hours).

If you set none of channels, channel_groups, uuids, or categories, the grant applies to the whole keyset. A request that sets none of read, write, manage, delete, get, update, or join fails validation with the message At least one flag should be specified. A request that combines uuids with channels or channel_groups fails validation with the message Grants for channels or channelGroups can't be changed together with grants for UUIDs. A request that sets uuids without auth_keys fails validation with the message UUIDs grant management require providing non empty authKeys.

Category permissions​

  • A category permission lets a token list all metadata of one resource type on your subscribe key. Valid categories are channels and uuids. The only permission is get (32).
  • A get permission on one named channel or user, or on a pattern, does not grant a category.
  • A token can contain only categories. It needs no resource or pattern.
  • When enumeration enforcement is enabled for a keyset, App Context list requests from a token or auth key without the matching category permission return a 403 error.

When you call categories():

  • Call get(True) to grant the category. Call get(False) with the same categories() and auth_keys() to revoke it.
  • The SDK leaves out every permission you don't set.
  • The get permission also applies to every channel, channel group, and uuid in the same request, because all resources in a request share one set of permissions.
  • Don't set read, write, manage, delete, update, or join to True.

Category grants need Python SDK 10.8.0 or later. future() resolves with a PubNubAsyncioException before the SDK sends the request in these cases:

CauseError message
categories() contains a value other than channels or uuids.Unsupported categories: <names>. Only 'channels' and 'uuids' are supported
auth_keys() is missing or empty.Category grants require providing non empty authKeys
read, write, manage, delete, update, or join is True.Category grants allow only the 'get' permission
get is True and ttl is 1.One-minute (ttl=1) category grants are not supported

Sample code​

Grant Access Manager permissions for channel and auth_key​

1envelope = await pubnub.grant().channels(["ch1", "ch2", "ch3"]).\
2 channel_groups(["cg1", "cg2"]).\
3 auth_keys(["key1", "key2"]).\
4 read(True).write(True).manage(True).\
5 future()

Returns​

grant() resolves with an AsyncioEnvelope whose result is a PNAccessManagerGrantResult and whose status is a PNStatus.

PNAccessManagerGrantResult​

level#
Type: str
Level of the grant that the service reports, for example subkey, channel, user, uuid, channel-group+auth, or category.
ttl#
Type: int
Time in minutes for which the permissions are valid.
subscribe_key#
Type: str
The subscribe key.
channels#
Type: dict
Access rights per channel, keyed by channel name. Each value is a PNAccessManagerChannelData.
groups#
Type: dict
Access rights per channel group, keyed by group name. Each value is a PNAccessManagerChannelGroupData.
uuids#
Type: dict
Access rights per uuid, keyed by uuid. Each value is a PNAccessManagerUuidsData with the same fields as PNAccessManagerChannelData.
categories#
Type: dict
Category-level access rights, keyed channels and uuids. Each value is a PNAccessManagerCategoryData with the same fields as PNAccessManagerChannelData, where name is the category name. Empty unless you set categories().
read_enabled#
Type: bool
Subscribe key level read permissions.
write_enabled#
Type: bool
Subscribe key level write permissions.
manage_enabled#
Type: bool
Subscribe key level manage permissions.
delete_enabled#
Type: bool
Subscribe key level delete permissions.

PNAccessManagerChannelData and PNAccessManagerChannelGroupData​

auth_keys#
Type: dict
Access rights per auth key, keyed by auth key. Each value is a PNAccessManagerKeyData.
name#
Type: str
Channel or group name.
read_enabled#
Type: bool
Channel or group level read permissions.
write_enabled#
Type: bool
Channel or group level write permissions.
manage_enabled#
Type: bool
Channel or group level manage permissions.
delete_enabled#
Type: bool
Channel or group level delete permissions.
get#
Type: bool
Channel, group, or category level get permissions. For a category, this is the only meaningful permission.
update#
Type: bool
Channel or group level update permissions.
join#
Type: bool
Channel or group level join permissions.
ttl#
Type: int
Time in minutes for which the permissions are valid.

PNAccessManagerKeyData​

read_enabled#
Type: bool
read permissions.
write_enabled#
Type: bool
write permissions.
manage_enabled#
Type: bool
manage permissions.
delete_enabled#
Type: bool
delete permissions.
get#
Type: bool
get permissions.
update#
Type: bool
update permissions.
join#
Type: bool
join permissions.
ttl#
Type: int
Time in minutes for which the permissions are valid.

The read, write, manage, delete, get, update, and join permissions have 3 states:

  • True if enabled.
  • False if disabled.
  • None if the response doesn't set them.
Requests size

Access Manager grant or revoke requests must be less than ~32 KiB at a time, or the client will return an error. For requests greater than 32 KiB, break them into smaller batched requests. When the message size exceeds 32 KiB the server returns the HTTP Error code 500, instead of the correct error code 414.

NTP configuration

Configure NTP on your server to keep its clock in sync. Clock drift causes a 400 Invalid Timestamp error response. See Why do I get "Invalid Timestamp" when I grant permissions?.

Other examples​

Grant an auth key access to list all channel and uuid metadata​

The code below grants my_auth_key the get category permission for both channels and uuids, with a 15 minute ttl.

1envelope = await pubnub.grant() \
2 .auth_keys(auth_key) \
3 .categories(['channels', 'uuids']) \
4 .get(True) \
5 .ttl(15) \
6 .future()
7if envelope.is_error():
8 print(f"Error: {envelope.status.error_data}")
9else:
10 print(f"Granted category permissions, level: {envelope.result.level}")

Grant subscribe privileges to all users on all channel(s) with default ttl (1440 minutes)​

1envelope = await pubnub.grant().read(True).write(True).future()
2if envelope.is_error():
3 print(f"Error: {envelope.status.error_data}")

Allow subscribe and publish to a specific channel for all users (no auth_key required) with default ttl (1440 minutes)​

1envelope = await pubnub.grant().channels("my_channel").read(True).write(True).future()
2if envelope.is_error():
3 print(f"Error: {envelope.status.error_data}")

Grant subscribe access to a channel only for clients with a specific auth_key with a 5 minute ttl​

1envelope = await pubnub.grant().channels("my_channel").read(True).write(False).\
2 auth_keys("my_ro_authkey").ttl(5).future()
3if envelope.is_error():
4 print(f"Error: {envelope.status.error_data}")

Allow access to a specific channel for Presence​

1envelope = await pubnub.grant(). \
2 channels("my_channel-pnpres").read(True).write(True).future()
3if envelope.is_error():
4 print(f"Error: {envelope.status.error_data}")

Grant Access Manager permissions for channel group​

1envelope = await pubnub.grant(). \
2 channel_groups(["cg1", "cg2", "cg3"]). \
3 auth_keys(["auth1", "auth2", "auth3"]). \
4 read(True).write(True).manage(True). \
5 ttl(12237). \
6 future()

Grant permissions on multiple channels​

1envelope = await pubnub.grant().\
2 auth_keys("my_rw_authkey").\
3 channels(["girish", "girish2"]).\
4 read(True).\
5 write(True).\
6 ttl(5).\
7 future()
Channel limit

The limit on the total amount of channels that you can pass at once when using grant() is 200.

Application level grant​

Use application level grants with caution

A grant at the application level gives access to all channels and users.

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.

After you close an application level grant with all flags set to False, it can take several minutes until the service refuses requests again.

1envelope = await pubnub.grant(). \
2 read(True).write(True). \
3 future()

Channel level grant​

1envelope = await pubnub.grant().channels("my_channel"). \
2 read(True).write(True). \
3 future()

User level grant​

1envelope = await pubnub.grant().channels("my_channel"). \
2 auth_keys("my_authkey"). \
3 read(True).write(True). \
4 ttl(5). \
5 future()

Was this page useful?

Last updated on