Access Manager v3 API for Python 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 allows you to enforce security controls for client access to resources within the PubNub Platform. With Access Manager v3, your servers (that use a PubNub instance configured with a secret key) can grant their clients tokens with embedded permissions that provide access to individual PubNub resources:

  • For a limited period of time.
  • Through resource lists or patterns (regular expressions).
  • In a single API request, even if permission levels differ (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.

Request execution and return values

You can decide whether to perform the Python SDK operations synchronously or asynchronously.

  • .sync() returns an Envelope object, which has two fields: Envelope.result, whose type differs for each API, and Envelope.status of type PnStatus.

    1pubnub.publish() \
    2 .channel("myChannel") \
    3 .message("Hello from PubNub Python SDK") \
    4 .sync()
  • .pn_async(callback) returns None and passes the values of Envelope.result and Envelope.status to a callback you must define beforehand.

    1def my_callback_function(result, status):
    2 print(f'TT: {result.timetoken}, status: {status.category.name}')
    3
    4pubnub.publish() \
    5 .channel("myChannel") \
    6 .message("Hello from PubNub Python SDK") \
    7 .pn_async(my_callback_function)
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.

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. See Enable the features your app calls.

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 grant_token() method generates a time-limited authorization token with an embedded access control list. The token defines time to live (ttl), authorized_uuid, and a set of permissions giving access to one or more resources:

  • channels
  • groups
  • uuids (other users' object metadata, such as their names or avatars)
  • categories (list all channel or uuid metadata on the subscribe key, not one named resource)

Only this authorized_uuid 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 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
channelsread, write, get, manage, update, join, delete
groupsread, manage
uuidsget, update, delete
categories (channels, uuids)get only

In grant_token(), categories takes Category.channels() and Category.uuids() values.

  • 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.

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

Method(s)​

1grant_token() \
2 .ttl(int) \
3 .meta(Dictionary) \
4 .authorized_uuid(str) \
5 .channels(list<Channel>) \
6 .groups(list<Group>) \
7 .uuids(list<UUID>) \
8 .categories(list<Category>)
* required
ParameterDescription
ttl *
Type: Number
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).
meta
Type: Dictionary
Default:
n/a
Extra metadata to be published with the request. Values must be scalar only; arrays or objects are not supported.
authorized_uuid
Type: Str
Default:
n/a
Single uuid which is authorized to use the token to make API requests to PubNub.
channels
Type: list<Channel>
Default:
n/a
All channel grants provided either as a list or a RegEx pattern.
groups
Type: list<Group>
Default:
n/a
All channel group grants provided either as a list or a RegEx pattern.
uuids
Type: list<UUID>
Default:
n/a
All uuid grants provided either as a list or a RegEx pattern.
categories
Type: list<Category>
Default:
n/a
Category grants that let the token list all metadata of a type on the subscribe key. Use Category.channels().get() to list all channel metadata and Category.uuids().get() to list all uuid metadata. A get permission on a named channel or uuid, or on a pattern, doesn't imply this. Refer to Category permissions.

Category permissions​

A category permission covers a whole resource type instead of individual resources. Listing all channels or uuids on a subscribe key needs one, because a get on a single resource doesn't allow it. Use Category.channels() for the channels category and Category.uuids() for the uuids category, and call get() on it. A category carries only the get permission.

  • 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.

grant_token() raises a PubNubException before the SDK sends the request in these cases:

CauseError message
A value isn't Category.channels() or Category.uuids().Unsupported category. Only Category.channels() and Category.uuids() are supported
A category doesn't have get() set, or has another permission set.Category permissions must be exactly the 'get' permission
Required key/value mappings

For a successful grant request, you must specify permissions for at least one uuid, channel, or group, either as a resource list or as a pattern (RegEx), or set categories. A categories grant alone satisfies this requirement.

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.
1import os
2from pubnub.pnconfiguration import PNConfiguration
3from pubnub.pubnub import PubNub
4from pubnub.models.consumer.v3.channel import Channel
5from pubnub.exceptions import PubNubException
6
7
8def grant_pubnub_token(pubnub: PubNub) -> str:
9 envelope = pubnub.grant_token() \
10 .channels([
11 Channel.id('readonly-channel').read(),
12 Channel.id('readwrite-channel').read().write(),
13 ]) \
14 .authorized_uuid("my-authorized-uuid") \
15 .ttl(15) \
show all 43 lines

Returns​

1{"token":"p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI"}

Other examples​

Grant an authorized client access to list all channel and uuid metadata​

The code below grants my-authorized-uuid the get category permission for both channels and uuids, so the client can list all channel and uuid metadata on the subscribe key.

1

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.
1from pubnub.models.consumer.v3.channel import Channel
2from pubnub.models.consumer.v3.group import Group
3from pubnub.models.consumer.v3.uuid import UUID
4
5channels = [
6 Channel.id("channel-a").read(),
7 Channel.id("channel-b").read().write(),
8 Channel.id("channel-c").read().write(),
9 Channel.id("channel-d").read().write()
10]
11groups = [
12 Group.id("channel-group-b").read()
13]
14uuids = [
15 UUID.id("uuid-c").get(),
show all 25 lines

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.

1envelope = pubnub.grant_token() \
2 .channels(Channel.pattern("channel-[A-Za-z0-9]").read()) \
3 .authorized_uuid("my-authorized-uuid") \
4 .ttl(15) \
5 .sync()

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.
1from pubnub.models.consumer.v3.channel import Channel
2from pubnub.models.consumer.v3.group import Group
3from pubnub.models.consumer.v3.uuid import UUID
4
5channels = [
6 Channel.id("channel-a").read(),
7 Channel.pattern("channel-[A-Za-z0-9]").read(),
8 Channel.id("channel-b").read().write(),
9 Channel.id("channel-c").read().write(),
10 Channel.id("channel-d").read().write()
11]
12groups = [
13 Group.id("channel-group-b").read()
14]
15uuids = [
show all 25 lines

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. Details are returned in the envelope object.

Grant token - spaces & users​

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 grantToken() method generates a time-limited authorization token with an embedded access control list. The token defines time to live (ttl), authorized_user, and a set of permissions giving access to one or more resources:

  • For a limited time period.
  • Through resource lists or regular expression (RegEx) patterns.
  • In one API request, even when permissions differ.

The grantToken() method generates a time-limited authorization token with an embedded access control list. The token defines time to live (ttl), authorized_user, 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 authorized_user 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 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
spaceread, write, get, manage, update, join, delete
userget, update, delete

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

Method(s)​

1grant_token() \
2 .ttl(Integer) \
3 .meta(Dictionary) \
4 .authorized_user(String) \
5 .spaces(list<Space>) \
6 .users(list<User>)
* required
ParameterDescription
ttl *
Type: Integer
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).
meta
Type: Dictionary
Default:
n/a
Extra metadata to be published with the request. Values must be scalar only; arrays or objects are not supported.
authorized_user
Type: String
Default:
n/a
Single user_id which is authorized to use the token to make API requests to PubNub.
spaces
Type: list<Space>
Default:
n/a
All Space permissions provided as a list of individual permissions or RegEx patterns.
users
Type: list<User>
Default:
n/a
All User permissions provided as a list of individual permissions or RegEx patterns.
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​

1envelope = pubnub.grant_token() \
2 .authorized_user('some_user_id')\
3 .spaces([
4 Space().id('some_space_id').read().write(),
5 Space().pattern('some_*').read().write()
6 ]) \
7 .ttl(60) \
8 .sync()

Returns​

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-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.
1from pubnub.models.consumer.v3.space import Space
2from pubnub.models.consumer.v3.user import User
3
4spaces = [
5 Space.id("space-a").read(),
6 Space.id("space-b").read().write(),
7 Space.id("space-c").read().write(),
8 Space.id("space-d").read().write()
9]
10users = [
11 User.id("userId-c").get(),
12 User.id("userId-d").get().update()
13]
14envelope = pubnub.grant_token()
15 .spaces(spaces)
show all 19 lines

Grant an authorized client read access to multiple spaces using RegEx​

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

1envelope = pubnub.grant_token()
2 .spaces(Space.pattern("space-[A-Za-z0-9]").read())
3 .ttl(15)
4 .authorized_user("my-authorized-userId")
5 .sync()

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

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.
1from pubnub.models.consumer.v3.space import Space
2from pubnub.models.consumer.v3.user import User
3
4channels = [
5 Space.id("space-a").read(),
6 Space.pattern("space-[A-Za-z0-9]").read(),
7 Space.id("space-b").read().write(),
8 Space.id("space-c").read().write(),
9 Space.id("space-d").read().write()
10]
11users = [
12 User.id("user-c").get(),
13 User.id("user-d").get().update()
14]
15envelope = pubnub.grant_token()
show all 21 lines

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. Details are returned in the envelope object.

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. See Enable the features your app calls.

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 revoke_token() 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 grant_token() 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)​

1revoke_token(String)
* required
ParameterDescription
token *
Type: String
Default:
n/a
Existing token with embedded permissions.

Sample code​

1pubnub.revoke_token("p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI")

Returns​

The revoke_token() operation returns an Envelope which contains the following fields:

FieldTypeDescription
resultPNRevokeTokenResultA detailed object containing the result of the operation.
statusPNStatusA status object with additional information.

PNRevokeTokenResult​

1Revoke token success with status: 200

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 parse_token() 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.

Method(s)​

1parse_token(String)
* required
ParameterDescription
token *
Type: String
Default:
n/a
Current token with embedded permissions.

Sample code​

1pubnub.parse_token("p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI")

Returns​

1{
2 "version":2,
3 "timestamp":1629394579,
4 "ttl":15,
5 "authorized_uuid": "user1",
6 "resources":{
7 "uuids":{
8 "user1":{
9 "read": False,
10 "write": False,
11 "manage": False,
12 "delete": False,
13 "get": True,
14 "update": True,
15 "join": False
show all 76 lines

Category permissions in parsed tokens​

A token granted with categories decodes them under a top-level categories key. Each entry holds one get flag, which is True only when the token can list all channel or uuid metadata:

1{
2 "categories":{
3 "channels":{ "get": True },
4 "uuids":{ "get": True }
5 }
6}

The categories key appears only when the token carries at least one category. An entry is absent when the token doesn't carry that category. The flags don't depend on named resource or pattern permissions.

The code below parses a token and reads its category permissions.

1

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 set_token() method is used by the client devices to update the authentication token granted by the server.

Method(s)​

1set_token(String)
* required
ParameterDescription
token *
Type: String
Default:
n/a
Current token with embedded permissions.

Sample code​

1pubnub.set_token("p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI")

Returns​

This method doesn't return any response value.

Was this page useful?

Last updated on