Access Manager v3 API for Dart 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).
Add the authorizedUuid parameter to restrict a token to one client with a UUID (universally unique identifier). Only this authorizedUUID can use the token to make API requests for the specified resources and permissions.
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. 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:
channelchannelGroupuuid(other users' object metadata, such as their names or avatars)user(DataSync users)entity,relationship, andmembership(DataSync entities, relationships, and memberships)
- 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 |
|---|---|
channel | read, write, create, get, manage, update, join, delete |
channelGroup | read, manage |
uuid | get, update, delete |
user (DataSync users) | create, get, update, delete |
entity, relationship, membership (DataSync) | create, get, update, delete |
read, write, manage, and join stay messaging concepts and are not available on user or on any DataSync resource. create on channel also authorizes provisioning a DataSync channel through createChannel.
DataSync user and channel objects are protected through the user and channel resource types, not through a separate DataSync scope. A grant on uuid does not authorize DataSync user operations, uuid remains scoped to App Context UUID metadata. Only DataSync entities, relationships, and memberships use their own resource types. Refer to DataSync access control for the full permission and resource-type mapping.
The SDK does not let one request combine user with uuid. Calling pubnub.grantToken for such a request throws an InvariantException before anything is sent.
For permissions and API operations mapping, refer to Manage Permissions with Access Manager v3.
The ttl (time to live) parameter is the number of minutes before the granted permissions expire. The client requires a new token before expiration to ensure continued 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 expressions (RegEx) to specify permissions by pattern instead of listing each resource. Set RegEx permissions as patterns before making a 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(TokenRequest tokenRequest)
To create TokenRequest:
1pubnub.requestToken({
2 int? ttl,
3 Map<String, dynamic>? meta,
4 String? authorizedUUID,
5 String? using,
6 Keyset? keyset
7});
The TokenRequest object has the following parameters:
| Parameter | Description |
|---|---|
ttl *Type: NumberDefault: n/a | Total number of minutes for which the token is valid.
|
metaType: Map<String, dynamic>Default: n/a | Extra metadata to be published with the request. Values must be scalar only; arrays or objects are not supported. |
authorizedUUIDType: String Default: n/a | Single uuid which is authorized to use the token to make API requests to PubNub. |
usingType: StringDefault: n/a | Keyset name from the keysetStore to be used for this method call. |
keysetType: KeysetDefault: n/a | Override for the PubNub default keyset configuration. |
Required key/value mappings
For a successful grant request, you must specify permissions for at least one uuid, channel, channelGroup, or DataSync resource, either as a resource list or as a pattern (RegEx). A projection assignment does not grant any permission by itself.
Use add() on TokenRequest to add resource or resource pattern permissions:
1add(ResourceType type,
2 {String? name,
3 String? pattern,
4 bool? create,
5 bool? delete,
6 bool? manage,
7 bool? read,
8 bool? write,
9 bool? get,
10 bool? update,
11 bool? join})
| Parameter | Description |
|---|---|
typeType: ResourceTypeDefault: n/a | Specify a resource type. It can be uuid, channel, or channelGroup (other value types are deprecated in App Context (formerly Objects v2) API), or one of the DataSync types user, entity, relationship, or membership. The DataSync types only support the create, get, update, and delete permissions. |
nameType: StringDefault: n/a | Specify a resource name, like uuid-a. Provide either name or pattern to specify permissions. |
patternType: StringDefault: n/a | Specify a resource pattern, like channel-[A-Za-z0-9]. Provide either name or pattern to specify permissions. |
writeType: BooleanDefault: false | Write permission |
readType: BooleanDefault: false | Read permission |
createType: BooleanDefault: false | Create permission |
manageType: BooleanDefault: false | Manage permission |
deleteType: BooleanDefault: false | Delete permission |
getType: BooleanDefault: false | Get permission |
updateType: BooleanDefault: false | Update permission |
joinType: BooleanDefault: false | Join permission |
Use addDataSyncProjection() on TokenRequest to assign a field-level DataSync projection to a resource or a resource pattern:
1addDataSyncProjection(ResourceType type,
2 {String? name,
3 String? pattern,
4 required String projection})
| Parameter | Description |
|---|---|
type *Type: ResourceTypeDefault: n/a | Resource type the projection applies to. It can be entity, relationship, membership, user, or channel. |
nameType: StringDefault: n/a | Identifier of a single resource, like product-sneaker-42. Provide either name or pattern. |
patternType: StringDefault: n/a | RegEx pattern matching the resources the projection applies to. Provide either name or pattern. |
projection *Type: StringDefault: n/a | Name of the projection. Pass the defaultProjection constant for the built-in __default__ base projection. |
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 built-in base projection, and exact id assignments take priority over pattern matches. 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 three distinct projection names in total, including __default__, so at most two custom names besides __default__.
addDataSyncProjection() throws an InvariantException on a type that cannot carry a projection, on a call that sets both name and pattern or neither, and on an empty projection, because a misspelled assignment would otherwise grant a token with the default view instead of the intended one. A projection assignment only decides which fields a create or update DataSync event includes for that token, refer to Add DataSync listener for the listener side.
Sample code
Reference code
1import 'package:pubnub/pubnub.dart';
2
3void main() async {
4 // Create PubNub instance with default keyset.
5 var pubnub = PubNub(
6 defaultKeyset: Keyset(
7 subscribeKey: 'demo',
8 publishKey: 'demo',
9 secretKey: 'sec_key'
10 userId: UserId('myUniqueUserId')
11 ),
12 );
13
14 // Prepare the request object for granting a token
15 var request = pubnub.requestToken(
show all 30 linesReturns
1{
2 "status": 200,
3 "data": {
4 "message": "Success",
5 "token": "p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI"
6 },
7 "service" : "Access Manager"
8}
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.
1var request = pubnub.requestToken(
2 ttl: 15, authorizedUUID: 'my-authorized-uuid')
3..add(ResourceType.channel, name: 'channel-a', read: true)
4..add(ResourceType.channelGroup, name: 'channel-group-b', read: true)
5..add(ResourceType.uuid, name: 'uuid-c', get: true)
6..add(ResourceType.channel, name: 'channel-b', read: true, write: true)
7..add(ResourceType.channel, name: 'channel-c', read: true, write: true)
8..add(ResourceType.channel, name: 'channel-d', read: true, write: true)
9..add(ResourceType.uuid, name: 'uuid-d', get: true, update: true);
10
11var token = await pubnub.grantToken(request);
12print('grant token = $token');
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.
1var request = pubnub.requestToken(
2 ttl: 15, authorizedUUID: 'my-authorized-uuid')
3..add(ResourceType.channel, pattern: 'channel-[A-Za-z0-9]', read: true);
4
5var token = await pubnub.grantToken(request);
6print('grant token = $token');
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.
1var request = pubnub.requestToken(
2 ttl: 15, authorizedUUID: 'my-authorized-uuid')
3..add(ResourceType.channel, name: 'channel-a', read: true)
4..add(ResourceType.channelGroup, name: 'channel-group-b', read: true)
5..add(ResourceType.uuid, name: 'uuid-c', get: true)
6..add(ResourceType.channel, name: 'channel-b', read: true, write: true)
7..add(ResourceType.channel, name: 'channel-c', read: true, write: true)
8..add(ResourceType.channel, name: 'channel-d', read: true, write: true)
9..add(ResourceType.uuid, name: 'uuid-d', get: true, update: true)
10..add(ResourceType.channel, pattern: 'channel-[A-Za-z0-9]', read: true);
11
12var token = await pubnub.grantToken(request);
13print('grant token = $token');
Grant an authorized client access to DataSync resources
The code below grants my-authorized-uuid:
- Create, get, update, and delete access to the entity
product-sneaker-42. - Create, get, update, and delete access to every membership matching the
membership-.*pattern. - Get access to the DataSync user
user-bobthrough the top-levelusertype, because DataSync users are not permissioned under a separate DataSync type.
1
Grant a token with a field-level projection
The code below grants my-authorized-uuid create, get, and update access to the entity product-sneaker-42, scoped to the admin projection, so events and reads through this token only see the fields the product class tags with admin.
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. The server returns the error details under the PubNubException 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. 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.
- For a limited time period.
- Through resource lists or regular expression (RegEx) patterns.
- In one API request, even when permissions differ (for example,
readtospace-1andwritetospace-2).
- Permissions
- TTL (time to live)
- RegEx patterns
- Authorized user ID
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 |
|---|---|
space | read, write, get, manage, update, join, delete |
user | get, update, delete |
For permissions and API operations mapping, refer to Manage Permissions with Access Manager v3.
The ttl (time to live) parameter is the number of minutes before permissions expire. The client requires a new token before expiration to ensure continued 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.
If you prefer to specify permissions by setting patterns, rather than listing all resources one by one, you can use regular expressions. To do this, set RegEx permissions as patterns before making a grant request.
For more details, see RegEx in Access Manager v3.
Setting an authorizedUserId in the token helps you specify which client device should use this token in every request to PubNub. This will ensure that all requests to PubNub are authorized before PubNub processes them. If authorizedUserId isn't specified during the grant request, the token can be used by any client with any userId. It's recommended to restrict tokens to a single authorizedUserId to prevent impersonation.
For more details, see Authorized UUID in Access Manager v3.
Method(s)
1pubnub.grantToken(TokenRequest tokenRequest)
To create TokenRequest:
1pubnub.requestToken({
2 int? ttl,
3 Map<String, dynamic>? meta,
4 String? authorizedUserId,
5 String? using,
6 Keyset? keyset
7});
The TokenRequest object has the following parameters:
| Parameter | Description |
|---|---|
ttl *Type: NumberDefault: n/a | Total number of minutes for which the token is valid.
|
metaType: Map<String, dynamic>Default: n/a | Extra metadata to be published with the request. Values must be scalar only; arrays or objects are not supported. |
authorizedUserIdType: String Default: n/a | Single userId which is authorized to use the token to make API requests to PubNub. |
usingType: StringDefault: n/a | Keyset name from the keysetStore to be used for this method call. |
keysetType: KeysetDefault: n/a | Override for the PubNub default keyset configuration. |
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).
Use add() on TokenRequest to add resource or resource pattern permissions:
1add(ResourceType type,
2 {String? name,
3 String? pattern,
4 bool? create,
5 bool? delete,
6 bool? manage,
7 bool? read,
8 bool? write,
9 bool? get,
10 bool? update,
11 bool? join})
| Parameter | Description |
|---|---|
typeType: ResourceTypeDefault: n/a | Specify a resource type. It can be user or space. |
nameType: StringDefault: n/a | Specify a resource name, like userId-a. Provide either name or pattern to specify permissions. |
patternType: StringDefault: n/a | Specify a resource pattern, like space-[A-Za-z0-9]. Provide either name or pattern to specify permissions. |
writeType: BooleanDefault: false | Write permission |
readType: BooleanDefault: false | Read permission |
createType: BooleanDefault: false | Create permission |
manageType: BooleanDefault: false | Manage permission |
deleteType: BooleanDefault: false | Delete permission |
getType: BooleanDefault: false | Get permission |
updateType: BooleanDefault: false | Update permission |
joinType: BooleanDefault: false | Join permission |
Sample code
1// Prepare the request object
2var request = pubnub.requestToken(ttl: 15, authorizedUserId: 'my-authorized-userId');
3request.add(ResourceType.space, name: 'my-space', read: true);
4
5// Send the token request
6var token = await pubnub.grantToken(request);
7print('grant token = $token');
Returns
1{
2 "status": 200,
3 "data": {
4 "message": "Success",
5 "token": "p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI"
6 },
7 "service" : "Access Manager"
8}
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-aand get tospace-c. - Read/write access to
space-b,space-c,space-d, and get/update touserId-d.
1var request = pubnub.requestToken(
2 ttl: 15, authorizedUserId: 'my-authorized-userId')
3..add(ResourceType.space, name: 'space-a', read: true)
4..add(ResourceType.user, name: 'userId-c', get: true)
5..add(ResourceType.space, name: 'space-b', read: true, write: true)
6..add(ResourceType.space, name: 'space-c', read: true, write: true)
7..add(ResourceType.space, name: 'space-d', read: true, write: true)
8..add(ResourceType.user, name: 'userId-d', get: true, update: true);
9
10var token = await pubnub.grantToken(request);
11print('grant token = $token');
Grant an authorized client read access to multiple spaces using RegEx
The code below grants my-authorized-userId read access to all spaces that match the space-[A-Za-z0-9] RegEx pattern.
1var request = pubnub.requestToken(
2 ttl: 15, authorizedUserId: 'my-authorized-userId')
3..add(ResourceType.space, pattern: 'space-[A-Za-z0-9]', read: true);
4
5var token = await pubnub.grantToken(request);
6print('grant token = $token');
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-aand get touser-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.
1var request = pubnub.requestToken(
2 ttl: 15, authorizedUserId: 'my-authorized-userId')
3..add(ResourceType.space, name: 'space-a', read: true)
4..add(ResourceType.user, name: 'userId-c', get: true)
5..add(ResourceType.space, name: 'space-b', read: true, write: true)
6..add(ResourceType.space, name: 'space-c', read: true, write: true)
7..add(ResourceType.space, name: 'space-d', read: true, write: true)
8..add(ResourceType.user, name: 'userId-d', get: true, update: true)
9..add(ResourceType.space, pattern: 'space-[A-Za-z0-9]', read: true);
10
11var token = await pubnub.grantToken(request);
12print('grant token = $token');
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. The server returns the error details under the PubNubException 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. 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)
1var result = await pubnub.revokeToken("token");
| Parameter | Description |
|---|---|
token *Type: StringDefault: n/a | Existing token with embedded permissions. |
Sample code
1await pubnub.revokeToken("token");
Returns
When the token revocation request is successful, this method returns an empty PamRevokeTokenResult.
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.
Method(s)
1parseToken(String token)
| Parameter | Description |
|---|---|
token *Type: StringDefault: n/a | Current token with embedded permissions. |
Sample code
1pubnub.parseToken("p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI")
Returns
1{
2 "version":2,
3 "timetoken":1629394579,
4 "ttl":15,
5 "authorizedUUID": "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 78 linesDataSync permissions and projections
The resources and patterns lists of a parsed token also hold the DataSync resources the token granted. Each Resource has a type (entity, relationship, or membership for DataSync entities, relationships, and memberships), a name or a pattern, and the boolean permission getters create, get, update, and delete. DataSync users and channels appear under the user and channel types. The projections list decodes the field-level projection assignments from the token metadata into Projection objects, each with a type, a name or a pattern, and the projection name.
A scope the SDK doesn't recognize is skipped instead of failing the whole parse, and projections is empty when the token carries none, so guard the access when you look for one.
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 setToken() method is used by the client devices to update the authentication token granted by the server.
Method(s)
1setToken(String token, {String? using, Keyset? keyset})
| Parameter | Description |
|---|---|
token *Type: StringDefault: n/a | Current token with embedded permissions. |
usingType: StringDefault: n/a | Keyset name from the keysetStore to be used for this method call. |
keysetType: KeysetDefault: n/a | Override for the PubNub default keyset configuration. |
Sample code
1pubnub.setToken("p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI")
Returns
This method doesn't return any response value.