Access Manager v3 API for Kotlin SDK
Access Manager isn't enabled by default
Breaking changes in v9.0.0
PubNub Kotlin SDK version 9.0.0 unifies the codebases for Kotlin and Java SDKs, introduces a new way of instantiating the PubNub client, and changes asynchronous API callbacks and emitted status events. These changes can impact applications built with previous versions (< 9.0.0 ) of the Kotlin SDK.
For more details about what has changed, refer to Java/Kotlin SDK migration guide.
Gradle compatibility
While older Gradle versions might work, we recommend using Gradle 6.8+ to ensure proper dependency resolution and avoid potential compatibility issues with the SDK's dependencies.
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 (
readtochannel1andwritetochannel2).
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.
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.
For more information about Access Manager v3, refer to Manage Permissions with Access Manager v3.
Request execution
Most PubNub Kotlin SDK method invocations return an Endpoint object, which allows you to decide whether to perform the operation synchronously or asynchronously.
You must invoke the .sync() or .async() method on the Endpoint to execute the request, or the operation will not be performed.
1val channel = pubnub.channel("channelName")
2
3channel.publish("This SDK rules!").async { result ->
4 result.onFailure { exception ->
5 // Handle error
6 }.onSuccess { value ->
7 // Handle successful method result
8 }
9}
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), the authorized user (authorizedUserId or authorizedUUID), and a set of permissions giving access to one or more resources:
channelschannelGroupsuuids(other users' object metadata, such as their names or avatars)users(DataSyncUserobjects)- DataSync entities, relationships, and memberships
Only the 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.
Don't mix uuids with users
users and uuids are separate token scopes: DataSync checks users, while App Context checks uuids. The two overloads keep them apart. UUIDGrant is not a TokenGrant, so the flat-list overload rejects it at compile time, and the legacy overload has no DataSync grants. A single grantToken() call therefore never carries both scopes.
- 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 |
|---|---|
channel | read, write, get, manage, update, join, delete |
channelGroups | read, manage |
uuids | get, update, delete |
users | create, get, update, delete |
| DataSync entities, relationships, memberships | create, get, update, delete |
read, write, manage, and join stay messaging concepts and are not available on users or on any DataSync resource.
DataSync user and channel objects are protected through the users and channels resource types, not through a separate DataSync scope. A grant under uuids does not authorize DataSync user operations. Only DataSync entities, relationships, and memberships use the DataSync scope. DataSyncGrant.user() and DataSyncGrant.channel() write their permissions into the users and channels scopes. Grants on the same id are merged, so combining a ChannelGrant and a DataSyncGrant.channel() grant on one id gives the token the union of both. That also means update = true on DataSyncGrant.channel() authorizes App Context channel metadata updates for the same id. Refer to DataSync access control for the full permission and resource-type mapping.
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 will require a new token to be granted before expiration to ensure continued access. ttl is a required parameter for every grant call and there is no default value set for it. The max value for ttl 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. 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 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 authorizedUUID isn't specified during the grant request, the token can be used by any client with any uuid. It's recommended to restrict tokens to a single authorizedUUID to prevent impersonation. The flat-list overload names the same setting authorizedUserId and takes a UserId.
For more details, see Authorized UUID in Access Manager v3.
Method(s)
- Flat-list (recommended)
- Legacy (for App Context)
1grantToken(
2 ttl: Int,
3 authorizedUserId: UserId? = null,
4 meta: CustomObject? = null,
5 grants: List<TokenGrant>,
6)
| Parameter | Description |
|---|---|
ttl *Type: IntDefault: n/a | Total number of minutes for which the token is valid.
|
authorizedUserIdType: UserIdDefault: n/a | Single user ID which is authorized to use the token to make API requests to PubNub. Omit it for a token any client can use. |
metaType: CustomObjectDefault: n/a | Extra metadata to be published with the request. Values must be scalar only; arrays or objects are not supported. Must be null or a map when any grant carries a projection, and must not contain the pn-projections key, because the SDK builds that key from the grants. |
grants *Type: List <TokenGrant>Default: n/a | Flat list of grants. Each grant's type selects its resource type: ChannelGrant, ChannelGroupGrant, or a grant created by the DataSyncGrant factory. |
TokenGrant
| Grant | Factory methods | Permissions you can set |
|---|---|---|
ChannelGrant | ChannelGrant.name() for an exact channel, ChannelGrant.pattern() for a RegEx pattern | read, write, manage, delete, create, get, join, update |
ChannelGroupGrant | ChannelGroupGrant.id() for an exact channel group, ChannelGroupGrant.pattern() for a RegEx pattern | read, manage |
DataSyncGrantType | The DataSyncGrant factory methods below | get, create, update, delete |
Every permission defaults to false, so set only the ones you want to grant. You cannot implement DataSyncGrantType yourself. Only the DataSyncGrant factory creates it, which stops a mistyped resource type from being silently dropped from the token.
Create DataSync grants with the DataSyncGrant factory. Each resource has a method for an exact id and a *Pattern method for a RegEx pattern, and all of them accept get, create, update, and delete:
| Factory method | Grants access to |
|---|---|
DataSyncGrant.entity(), DataSyncGrant.entityPattern() | DataSync entities. |
DataSyncGrant.relationship(), DataSyncGrant.relationshipPattern() | DataSync relationships. |
DataSyncGrant.membership(), DataSyncGrant.membershipPattern() | DataSync memberships. These grants take no projection, because the built-in Membership class declares no named projections. |
DataSyncGrant.channel(), DataSyncGrant.channelPattern() | DataSync channels, through the channels scope. |
DataSyncGrant.user(), DataSyncGrant.userPattern() | DataSync users, through the users scope. |
DataSyncGrant.subscribe(), DataSyncGrant.subscribePattern() | Real-time subscribe to the data channel of a DataSync user, channel, or entity. Returns a ChannelGrant with read on the resolved channel. |
Projections control which payload fields a token can read and write on a DataSync resource. The entity, relationship, channel, and user grants take an optional projection, the name of the single projection the token holder looks through for that resource. Omit it to use the built-in __default__ projection, and exact id assignments take priority over pattern matches. Refer to the DataSync projections guide for how a token selects a projection. The SDK writes the assignments into the token meta under pn-projections for you.
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__. The built-in User and Channel classes expose their fields through __default__ only, so a named projection on a user or channel grant only has an effect for a custom subclass that declares it.
Projections filter real-time events too, but the projection of a DataSyncGrant.subscribe() grant only selects the channel name, __{projection}__{id}, and adds nothing to the token. To read through a projection and subscribe to it, grant both. Refer to Add DataSync listener.
Use the legacy overload when the token carries App Context uuids permissions. For DataSync-related permissions, use the flat-list overload.
1grantToken(
2 ttl: Int,
3 meta: CustomObject? = null,
4 authorizedUUID: String? = null,
5 channels: List<ChannelGrant> = emptyList(),
6 channelGroups: List<ChannelGroupGrant> = emptyList(),
7 uuids: List<UUIDGrant> = emptyList()
8)
| Parameter | Description |
|---|---|
ttl *Type: NumberDefault: n/a | Total number of minutes for which the token is valid.
|
metaType: ObjectDefault: n/a | Extra metadata to be published with the request. Values must be scalar only; arrays or objects are not supported. |
authorizedUUIDType: StringDefault: n/a | Single uuid which is authorized to use the token to make API requests to PubNub. |
channelsType: list<Channel>Default: n/a | All channel grants provided either as a list or a RegEx pattern. |
channelGroupsType: list<ChannelGroupGrant>Default: n/a | All channel group grants provided either as a list or a RegEx pattern. |
uuidsType: list<UUIDGrant>Default: n/a | All uuid grants provided either as a list or a RegEx pattern. UUIDGrant carries only get, update, and delete. |
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). The SDK fails a call with an empty grants list, or with no grants at all in the legacy overload, before it sends anything.
Sample code
Reference code
1
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-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 a token with the flat-list overload
The code below grants my-authorized-user-id read and write access to channel-a and read access to channel-group-b in a single grants list.
1
Grant an authorized client access to DataSync resources
The code below grants my-authorized-user-id:
- Get, create, update, and delete access to the DataSync entity
product-sneaker-42. - Get access to the DataSync relationship
rel-bob-owns-sneaker-42. - Get access to the DataSync membership
membership-alice-summer-sale. - Get access to the DataSync user
user-bobthrough the top-levelusersscope, because DataSync users are not permissioned under the DataSync scope. - Read access to the data channel of
product-sneaker-42, so the client can subscribe to its real-time updates.
1
Grant access to DataSync resources using RegEx
The code below grants my-authorized-user-id get access to every DataSync entity whose id matches product-.*, and read access to the data channels of the same entities.
1
Grant a token with a field-level projection
The code below grants my-authorized-user-id the same access to product-sneaker-42 as above and assigns the admin projection to it. With that projection, the client reads and writes only the fields the admin projection exposes. The matching DataSyncGrant.subscribe() grant lets the client subscribe to the admin projection channel, __admin__product-sneaker-42.
1
Error responses
If you submit an invalid request, the server returns the 400 error status code with a descriptive message informing which of the provided arguments is missing or incorrect. These can include, for example, issues with a RegEx, a timestamp, or permissions. The server returns the details of the error as a string under the PubNubException class.
The SDK also rejects some requests locally, with a PubNubException, before it sends anything. That happens when the grant list is empty, when meta already contains pn-projections, or when a grant carries a projection and meta is neither null nor a map.
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)
1revokeToken(token: String)
| 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 Unit.
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{
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 linesDataSync permissions and projections
A token granted with users or DataSync permissions decodes those scopes as well. The resources and patterns of the returned PNToken gain the users, datasyncEntities, datasyncRelationships, and datasyncMemberships maps, and each PNResourcePermissions gains a create flag. DataSync scopes carry only the four CRUD flags, create, get, update, and delete.
Projections come back twice. The raw block stays under meta on the pn-projections key, where each entry is a composite datasync:<kind>:<id> key mapped to the projection name. The same data is also lifted into the typed projections property, which holds a resources scope and a patterns scope, each with entities, relationships, and memberships maps of bare id to projection name:
1{
2 "resources":{
3 "users":{
4 "user-bob":{ "create":false, "get":true, "update":false, "delete":false }
5 },
6 "datasyncEntities":{
7 "product-sneaker-42":{ "create":true, "get":true, "update":true, "delete":false }
8 }
9 },
10 "patterns":{
11 "datasyncEntities":{
12 "product-.*":{ "create":false, "get":true, "update":false, "delete":false }
13 }
14 },
15 "meta":{
show all 25 linesProjection assignments made through DataSyncGrant.user() and DataSyncGrant.channel() are not decoded into projections. They remain available only in the raw meta block, under datasync:users:<id> and datasync:channels:<id> keys. The projections property is null when the token has no pn-projections block, and a scope the token did not grant decodes as an empty map.
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)
| Parameter | Description |
|---|---|
token *Type: StringDefault: n/a | Current token with embedded permissions. |
Sample code
1
Returns
This method doesn't return any response value.