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.
| Resource | Permissions |
|---|---|
channel | read, write, get, manage, update, join, delete |
uuid | get, update, delete |
channel_group | read, 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
channelsanduuids. The only permission isget(32). - A
getpermission 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
403error.
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 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 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:
- Application Level - Access Manager privileges are always evaluated first at the
Applicationlevel. If thereadorwriteattribute isTruefor a subscribe key, Access Manager grants access for that attribute immediately and doesn't check theChannelorUserlevels. If an attribute isFalseat the Application level, Access Manager proceeds to evaluate the attribute at the next most granular level. - Channel Level - After first verifying an attribute at the Application level, Access Manager evaluates the attribute at the Channel level. If an attribute is
Truefor a combination of subscribe key and channel, Access Manager grants access for that attribute at theChannellevel and doesn't check theUserlevel. - User Level (Recommended) - As a final step, Access Manager evaluates the attributes at the
Userlevel. If an attribute isTruefor 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#- 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 forcategories. Without them, the permissions apply to all clients on channel level or application level. See Grant levels. channels#- 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#- Channel groups on which to grant permissions. This parameter does not support wildcards.
uuids#- 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 useuuids. This parameter does not support wildcards. categories#- Categories to grant. Valid values are
channels, which lists all channel metadata, anduuids, which lists all uuid metadata. Agetpermission on a named channel or uuid doesn't imply this. Requiresauth_keys. Refer to Category permissions. read#- Pass
Trueto grantreadpermissions orFalseto remove them. If you don't call the method, the SDK doesn't send the flag, and any other value counts asFalse. write#- Pass
Trueto grantwritepermissions orFalseto remove them. If you don't call the method, the SDK doesn't send the flag, and any other value counts asFalse. manage#- Pass
Trueto grantmanagepermissions orFalseto remove them. If you don't call the method, the SDK doesn't send the flag, and any other value counts asFalse. delete#- Pass
Trueto grantdeletepermissions orFalseto remove them. If you don't call the method, the SDK doesn't send the flag, and any other value counts asFalse. get#- Pass
Trueto grantgetpermissions orFalseto remove them. If you don't call the method, the SDK doesn't send the flag, and any other value counts asFalse. update#- Pass
Trueto grantupdatepermissions orFalseto remove them. If you don't call the method, the SDK doesn't send the flag, and any other value counts asFalse. join#- Pass
Trueto grantjoinpermissions orFalseto remove them. If you don't call the method, the SDK doesn't send the flag, and any other value counts asFalse. ttl#- 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
channelsanduuids. The only permission isget(32). - A
getpermission 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
403error.
When you call categories():
- Call
get(True)to grant the category. Callget(False)with the samecategories()andauth_keys()to revoke it. - The SDK leaves out every permission you don't set.
- The
getpermission 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, orjointoTrue.
Category grants need Python SDK 10.8.0 or later. future() resolves with a PubNubAsyncioException before the SDK sends the request in these cases:
| Cause | Error 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#- Level of the grant that the service reports, for example
subkey,channel,user,uuid,channel-group+auth, orcategory. ttl#- Time in minutes for which the permissions are valid.
subscribe_key#- The subscribe key.
channels#- Access rights per channel, keyed by channel name. Each value is a
PNAccessManagerChannelData. groups#- Access rights per channel group, keyed by group name. Each value is a
PNAccessManagerChannelGroupData. uuids#- Access rights per uuid, keyed by uuid. Each value is a
PNAccessManagerUuidsDatawith the same fields asPNAccessManagerChannelData. categories#- Category-level access rights, keyed
channelsanduuids. Each value is aPNAccessManagerCategoryDatawith the same fields asPNAccessManagerChannelData, wherenameis the category name. Empty unless you setcategories(). read_enabled#- Subscribe key level
readpermissions. write_enabled#- Subscribe key level
writepermissions. manage_enabled#- Subscribe key level
managepermissions. delete_enabled#- Subscribe key level
deletepermissions.
PNAccessManagerChannelData and PNAccessManagerChannelGroupData
auth_keys#- Access rights per auth key, keyed by auth key. Each value is a
PNAccessManagerKeyData. name#- Channel or group name.
read_enabled#- Channel or group level
readpermissions. write_enabled#- Channel or group level
writepermissions. manage_enabled#- Channel or group level
managepermissions. delete_enabled#- Channel or group level
deletepermissions. get#- Channel, group, or category level
getpermissions. For a category, this is the only meaningful permission. update#- Channel or group level
updatepermissions. join#- Channel or group level
joinpermissions. ttl#- Time in minutes for which the permissions are valid.
PNAccessManagerKeyData
The read, write, manage, delete, get, update, and join permissions have 3 states:
Trueif enabled.Falseif disabled.Noneif 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()