Access Manager v3 API for PHP SDK
Access Manager isn't enabled by default
Access Manager v3 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 (
readtochannel1andwritetochannel2).
You can add the authorizedUuid parameter to the grant request to restrict the token usage to only one client with a given Uuid. 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.
For more information about Access Manager v3, refer to Manage Permissions with Access Manager v3.
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 grantToken() 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:
ChannelsChannelGroupsUuids(other users' object metadata, such as their names or avatars)DataSync(DataSync entities, relationships, and memberships)Categories(list all channel or uuid metadata on the subscribe key, not one named resource)
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 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 |
|---|---|
Channels | read, write, create, get, manage, update, join, delete |
ChannelGroups | read, manage |
Uuids | get, update, delete |
DataSync (entities, relationships, memberships) | create, get, update, delete |
Categories (PNGrantCategory::CHANNELS, PNGrantCategory::UUIDS) | get only |
In grantToken(), categories() sets 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.
read, write, manage, and join stay messaging concepts and are not available on any DataSync resource. create on Channels also authorizes provisioning a DataSync channel entity through createChannel.
DataSync user and channel objects are protected through the users and channels resource types, not through the DataSync scope. A grant under Uuids does not authorize DataSync user operations, Uuids remains scoped to App Context UUID metadata. Only DataSync entities, relationships, and memberships use the DataSync scope. Refer to DataSync access control for the full permission and resource-type mapping.
The PHP grant builder has no users resource type
The grantToken() builder has no method for the users resource type, and addUuidResources grants the uuids type, which DataSync does not check for user operations. A token from this builder therefore cannot authorize DataSync user operations, while channel entities are covered by addChannelResources. To work with DataSync users from PHP, sign the requests with a client configured with a secret key instead. dataSyncProjections can still assign a projection to a user id.
For permissions and API operations mapping, refer to Manage Permissions with Access Manager v3.
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 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 authorizedUuid isn't specified 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)
1$pubnub->grantToken()
2 ->ttl($ttl)
3 ->authorizedUuid($uuid)
4 ->addChannelResources(Array[String => String])
5 ->addChannelGroupResources(Array[String => String])
6 ->addUuidResources(Array[String => String])
7 ->addDataSyncEntityResources(Array[String => Array])
8 ->addDataSyncRelationshipResources(Array[String => Array])
9 ->addDataSyncMembershipResources(Array[String => Array])
10 ->addChannelPatterns(Array[String => String])
11 ->addChannelGroupPatterns(Array[String => String])
12 ->addUuidPatterns(Array[String => String])
13 ->addDataSyncEntityPatterns(Array[String => Array])
14 ->addDataSyncRelationshipPatterns(Array[String => Array])
15 ->addDataSyncMembershipPatterns(Array[String => Array])
show all 20 lines| Parameter | Description |
|---|---|
ttl *Type: NumberDefault: 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. |
addChannelResourcesType: ArrayDefault: n/a | Array containing explicit channels resource permissions. |
addChannelGroupResourcesType: ArrayDefault: n/a | Array containing explicit channel groups resource permissions. |
addUuidResourcesType: ArrayDefault: n/a | Array containing explicit UUID resource permissions. App Context UUID metadata only, does not authorize DataSync users. |
addDataSyncEntityResourcesType: ArrayDefault: n/a | Array containing explicit DataSync entity permissions, keyed by entity id. |
addDataSyncRelationshipResourcesType: ArrayDefault: n/a | Array containing explicit DataSync relationship permissions, keyed by relationship id. |
addDataSyncMembershipResourcesType: ArrayDefault: n/a | Array containing explicit DataSync membership permissions, keyed by membership id. |
addChannelPatternsType: ArrayDefault: n/a | Array containing channels permissions expressed as a RegEx pattern. |
addChannelGroupPatternsType: ArrayDefault: n/a | Array containing channel groups permissions expressed as a RegEx pattern. |
addUuidPatternsType: ArrayDefault: n/a | Array containing UUID permissions expressed as a RegEx pattern. |
addDataSyncEntityPatternsType: ArrayDefault: n/a | Array containing DataSync entity permissions expressed as a RegEx pattern. |
addDataSyncRelationshipPatternsType: ArrayDefault: n/a | Array containing DataSync relationship permissions expressed as a RegEx pattern. |
addDataSyncMembershipPatternsType: ArrayDefault: n/a | Array containing DataSync membership permissions expressed as a RegEx pattern. |
categoriesType: ArrayDefault: n/a | Category grants that let the token list all metadata of a type on the subscribe key. Keys are PNGrantCategory::CHANNELS (list all channel metadata) and PNGrantCategory::UUIDS (list all uuid metadata). Each value is an array with 'get' => true. A get permission on a named channel or uuid, or on a pattern, doesn't imply this. A later call replaces the categories of an earlier call. Refer to Category permissions. |
dataSyncProjectionsType: ArrayDefault: n/a | Field-level projection assignments for DataSync resources and patterns. |
metaType: ArrayDefault: n/a | Extra metadata to be published with the request. Values must be scalar only; arrays or objects aren't supported. |
An array for resource/permission should contain the resource name as the key and an array of rights as a value. You don't need to specify the false permissions as that's the default value for all rights.
1[
2 'channel-1' => ['read' => true, 'write' => true]
3 'channel-2' => ['read' => true, 'write' => false]
4 'channel-3' => ['read' => true]
5]
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__.
dataSyncProjections takes up to two scopes, resources for exact ids and patterns for RegEx patterns. Each scope holds any of entities, users, channels, relationships, and memberships, mapped from an id (or pattern) to a projection name. The SDK throws a PubNubValidationException on an unknown scope or family and on an empty projection name, because a misspelled key 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.
1[
2 'resources' => ['entities' => ['product-sneaker-42' => 'admin']],
3 'patterns' => ['memberships' => ['membership-.*' => '__default__']],
4]
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 PNGrantCategory::CHANNELS for the channels category and PNGrantCategory::UUIDS for the uuids category. 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
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.
categories() throws a PubNubValidationException before the SDK sends the request in these cases:
| Cause | Error message |
|---|---|
The key is not channels or uuids. | unknown category "<name>", expected one of: channels, uuids |
| The value is not an array of permission flags. | category "<name>" must map a permission name to a flag |
A permission other than get is true. | category "<name>" accepts only the get permission, "<permission>" given |
A category with 'get' => false is left out of the token.
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), or a dataSyncProjections assignment. A categories grant alone also satisfies this requirement.
Sample code
Reference code
1
Returns
1"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 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 channel
channel-summer-salethrough thechannelsscope, because DataSync channels are not permissioned underDataSync.
1
Grant an authorized client access to list all channel and uuid metadata
The code below grants regular-user the get category permission for both channels and uuids, so the client can list all channel and uuid metadata on the subscribe key. It then parses the token and checks both categories.
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 in PubNubServerException.
| Method | Description |
|---|---|
getStatusCode()Type: Int | Status code 400 that is returned by the server by default. |
getBody()Type: Object | Entire body of the error returned by the server. The body contains such fields as message, source, details, service, and status. |
getServerErrorMessage()Type: String | Descriptive error message, such as Invalid ttl. |
getServerErrorSource()Type: String | Source of the error. |
getServerErrorDetails()Type: Object | Details of the first encountered problem. This object contains these public properties: message, location, and locationType. |
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 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)
1$pubnub->revokeToken($token)
2 ->sync();
| Parameter | Description |
|---|---|
token *Type: StringDefault: n/a | Existing token with embedded permissions. |
Sample code
1
Returns
When the token revocation request is successful, this method returns a PNRequestResult. When the request fails, it returns PubNubServerException.
PNRequestResult
| Method | Description |
|---|---|
getStatus()Type: Int | Server response status 200. |
getService()Type: String | Service to which the request was made. In this case, Access Manager. |
isError()Type: Boolean | Whether the response is an error message. |
getError()Type: Array | Error returned by the server. |
getMessage()Type: String | Message returned by the server on successful request. In this case, Success. |
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
1
Returns
1$parsedToken = $pubnub->parseToken( "p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI")
2->toArray();
3
4array(7) {
5 ["version"]=>
6 int(2)
7 ["timestamp"]=>
8 int(1634592012)
9 ["ttl"]=>
10 int(15)
11 ["resources"]=>
12 array(1) {
13 ["chan"]=>
14 array(1) {
15 ["my-channel"]=>
show all 43 lines| Method | Parameter | Return type | Description |
|---|---|---|---|
getVersion() | none | Int | Token version. The current version is 2. |
getTimestamp() | none | Int | Timestamp of the issued token. |
getTtl() | none | String | Total number of minutes for which the token is valid. |
getResources() | none | Array | List of all resources included in the token in the following format: type => name => permissions |
getPatterns() | none | Array | List of all patterns included in the token in the following format: type => name => permissions |
getChannelResource($channel) | String | Object | Instance of the Permissions object for a specific channel. It returns null if no permissions are defined. |
getChannelGroupResource($channelGroup) | String | Object | Instance of the Permissions object for a specific channel group. It returns null if no permissions are defined. |
getUuidResource($uuid) | String | Object | Instance of the Permissions object for a specific UUID. It returns null if no permissions are defined. |
getChannelPattern($channel) | String | Object | Instance of the Permissions object for a specific channel. It returns null if no permissions are defined. |
getChannelGroupPattern($channelGroup) | String | Object | Instance of the Permissions object for a specific channel group. It returns null if no permissions are defined. |
getUuidPattern($uuid) | String | Object | Instance of the Permissions object for a specific UUID. It returns null if no permissions are defined. |
getChannelsCategory() | none | Object | Instance of the Permissions object for the channels category. hasGet() is true when the token can list all channel metadata. It returns false if the token has no channels category. |
getUuidsCategory() | none | Object | Instance of the Permissions object for the uuids category. hasGet() is true when the token can list all uuid metadata. It returns false if the token has no uuids category. |
getCategories() | none | Array | Raw category permissions in the format type => rights, where type is chan or uuid and rights is the permission bitmask (32 is get). It returns an empty array if the token has no categories. |
getDataSyncEntityResource($id) | String | Object | Instance of the Permissions object for a specific DataSync entity. It returns false if no permissions are defined. |
getDataSyncRelationshipResource($id) | String | Object | Instance of the Permissions object for a specific DataSync relationship. It returns false if no permissions are defined. |
getDataSyncMembershipResource($id) | String | Object | Instance of the Permissions object for a specific DataSync membership. It returns false if no permissions are defined. |
getDataSyncEntityPattern($pattern) | String | Object | Instance of the Permissions object for a DataSync entity pattern. It returns false if no permissions are defined. |
getDataSyncRelationshipPattern($pattern) | String | Object | Instance of the Permissions object for a DataSync relationship pattern. It returns false if no permissions are defined. |
getDataSyncMembershipPattern($pattern) | String | Object | Instance of the Permissions object for a DataSync membership pattern. It returns false if no permissions are defined. |
getDataSyncProjections() | none | Object | Instance of PNDataSyncProjections with the projection assignments in the token. It returns null if the token has none. |
getMetadata() | none | Array | Array of metadata set in the grant token request. |
getSignature() | none | String | Signature generated by the server. |
getUuid() | none | String | Authorized UUID |
toArray() | none | Array | Entire token in an array format |
Permissions object
Calling getChannelResource() returns an instance of the Permissions object. This object has a series of methods to access specific rights.
1
| Method | Return type | Description |
|---|---|---|
hasRead() | boolean | read rights that apply to Subscribe, History, and Presence. |
hasWrite() | boolean | write rights that apply to Publish. |
hasManage() | boolean | manage rights that apply to channel groups and App Context. |
hasDelete() | boolean | delete rights that apply to History and App Context. |
hasGet() | boolean | get rights that apply to App Context (formerly Objects v2). |
hasUpdate() | boolean | update rights that apply to App Context (formerly Objects v2). |
hasJoin() | boolean | join rights that apply to App Context (formerly Objects v2). |
hasCreate() | boolean | create rights that apply to App Context (formerly Objects v2) and DataSync. |
For example, calling hasRead() returns true.
DataSync permissions and projections
The getDataSync*Resource() and getDataSync*Pattern() methods decode the DataSync CRUD permissions embedded in the token. getDataSyncProjections() decodes the field-level projection assignments from the token's pn-projections metadata into a PNDataSyncProjections object. Its getResources() and getPatterns() methods each return a PNDataSyncProjectionScope, which exposes getEntities(), getUsers(), getChannels(), getRelationships(), and getMemberships() as id-to-projection maps, and getEntityProjection($id), getUserProjection($id), getChannelProjection($id), getRelationshipProjection($id), and getMembershipProjection($id) for a single id. toArray() adds a projections key to its output when the token carries them.
The DataSync getters return false and getDataSyncProjections() returns null when the token didn't grant them, so guard the access when you read one.
1
Category permissions in parsed tokens
getChannelsCategory() and getUuidsCategory() return a Permissions object, so hasGet() tells you whether the token can list all metadata of that type. The flags don't depend on named resource or pattern permissions. toArray() adds a categories key, keyed chan and uuid, only when the token carries categories. The category grant example shows both getters.
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)
| Parameter | Description |
|---|---|
token *Type: StringDefault: n/a | Current token with embedded permissions. |
Sample code
1
Returns
This method doesn't return any response value.