Access Manager v2 API for Kotlin SDK
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.
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.
As soon as Access Manager is enabled, no publish/subscribe operations can be done without first explicitly providing an authorization token to the PubNub object. If an invalid token is provided, the requesting client will receive a Forbidden error.
For more information about Access Manager, refer to Managing Permissions with Access Manager.
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
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 authKeys. You may need to make multiple grant calls with an authKey so that you can specify explicit permissions for each channel, channelGroup and uuid resources. For common permissions, you can normally use a single request.
Privileges specifically granted to an application's subscribeKey always take precedence over privileges granted to channel or auth_key. Therefore an application that requires authentication at the user level should not grant access at either the Application or Channel levels. View the Grant Levels section for more details.
Permissions
The grant request allows your server to securely grant access for your clients on the following resources within the platform. Each resource allows a limited set of permissions that control the operations that can be performed by the clients. For permissions and API operations mapping information, refer to Managing Permissions with Access Manager
| Resource | Permissions |
|---|---|
channel | read, write, get, manage, update, join, delete |
uuid | get, update, delete |
channelGroup | read, manage |
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 only 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 initially used wildcards to grant permissions to a.*.
Grant levels
When a user attempts to access a PubNub resource, Access Manager will evaluate any existing rules using the following order of precedence before access to a channel is granted to the user:
- Application Level - Access Manager privileges are always evaluated first at the
Applicationlevel. If eitherreadorwriteattribute is set totruefor asubscribeKey, Access Manager will immediately grant access for that attribute without proceeding to check permissions at eitherChannelorUserlevels. If an attribute is set tofalseat 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 set to
truefor a combination ofsubscribeKey, andchannel, Access Manager grants access for that attribute at theChannellevel without proceeding to check whether there may beuserlevel permissions. - User Level (Recommended) - As a final step Access Manager evaluates the attributes at the
Userlevel. If an attribute is set totrueforsubscribeKey,channelandauth_key, access is granted for that attribute. Similarly, user level grants also allow you granting anauth_keyaccess tochannelGroupsanduuids. User level grants requireauth_keyand are the recommended approach if you need to manage permissions for individual users within your application. Each user should be assigned a uniqueauth_keyand securely passed back to the user to perform operations on the platform.
Method(s)
To Grant Permissions on a Channel you can use the following method(s) in the Kotlin SDK:
1this.pubnub.grant(
2 authKeys: List<String>,
3 channels: List<String>,
4 channelGroups: List<String>,
5 write: Boolean,
6 read: Boolean,
7 manage: Boolean,
8 delete: Boolean,
9 ttl: Int,
10 getAllChannels: Boolean = false,
11 getAllUUIDs: Boolean = false
12).async { result -> }
authKeys#- Specifies
authKeyto grant permissions to.
It's possible to specify multiple auth keys.
You can also grant access to a singleauthKeyfor multiplechannelsat the same time. Zero or morechannelswith zero or moreauthtokens are allowed. channels#- Specifies the
channelson which to grant permissions.
If nochannels/channelGroupsare specified, then the grant applies to allchannels/channelGroupsthat have been or will be created for that publish/subscribe key set.
Furthermore, any existing or future grants on specificchannelsare ignored, until the allchannelsgrant is revoked.
It's possible to grant permissions to multiplechannelssimultaneously.
Wildcard notation likea.*can be used to grant access onchannels. You can grant one level deep.
-a.*- you can grant on this.
-*anda.b.*- grant will not work on these levels. If you grant on*ora.b.*, the grant will treat*ora.b.*as a single channel named either*ora.b.*. channelGroups#- Specifies the
channelGroupstograntpermissions. If nochannels/channelGroupsare specified, then thegrantapplies to allchannels/channelGroupsthat have been or will be created for that publish/subscribe key set.
Furthermore, any existing or future grants on specificchannelGroupsare ignored, until theall channelGroupsgrant is revoked.
It's possible tograntpermissions to multiplechannelGroupssimultaneously. write#- Write permission
read#- Read permission
manage#- Manage permission
delete#- Delete permission
ttl#- Time in minutes for which granted permissions are valid. Setting
ttlto 0 will apply the grant indefinitely, which is also the default behavior. getAllChannels#- Set to
trueto allow theauthKeysto list all channel metadata on the keyset withgetAllChannelMetadata(). Agetpermission on a named channel doesn't imply this. Refer to Category permissions. getAllUUIDs#- Set to
trueto allow theauthKeysto list all uuid metadata on the keyset withgetAllUUIDMetadata(). Agetpermission on a named uuid doesn't imply this. Refer to Category permissions. sync#- Fires the request, locks the thread, and throws an exception if something goes wrong.
async#- Fires the request asynchronously and reports back with a callback.
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.
getAllChannels covers the channels category and getAllUUIDs covers the uuids category. When either flag is true:
- The SDK sends the
getpermission for you. - 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. - The server rejects the request if you set any other permission.
- The server returns a
400error for a category grant withgetset totrueand attlof1. The SDK doesn't check this before sending.
The SDK always sends get as true when a category flag is true, so it can't send a category-only revoke. The SDK also sends this get permission for every other resource in the same call. To remove the category permissions, revoke all permissions for the authKey with grant(authKeys = listOf(key)), which also removes its other key-wide permissions.
Sample code
Grant Access Manager permissions for channel and auth_key
1pubnub.grant(
2 channels = listOf("ch1", "ch2", "ch3"), //channels to allow grant on
3 channelGroups = listOf("cg1", "cg2", "cg3"), // groups to allow grant on
4 authKeys = listOf("key1", "key2", "key3"), // the keys we are provisioning
5 write = true, // allow those keys to write (false by default)
6 manage = true, // allow those keys to manage channel groups (false by default)
7 read = true, // allow keys to read the subscribe feed (false by default)
8 delete = true, // allow keys to delete messages (false by default)
9 ttl = 12337 // how long those keys will remain valid (0 for eternity)
10).async { result ->
11 // result is a parsed and abstracted response from server
12}
Returns
The grant() operation returns a PNAccessManagerGrantResult? which contains the following operations:
level#- Permissions level, one of
subkey,subkey+auth,channel,channel-group,channel-group+authlevel. subscribeKey#- The
subscribeKey. channels#- Access rights per channel. See PNAccessManagerKeyData for more details.
channelGroups#- Access rights per channel group. See PNAccessManagerKeyData for more details.
categories#- Category-level access rights, keyed
channelsanduuids. See PNAccessManagerKeyData for more details. Empty unless you setgetAllChannelsorgetAllUUIDs.
PNAccessManagerKeyData
readEnabled#- Is
trueif read rights are granted writeEnabled#- Is
trueif write rights are granted manageEnabled#- Is
trueif manage rights are granted deleteEnabled#- Is
trueif delete rights are granted getEnabled#- Is
trueif get rights are granted updateEnabled#- Is
trueif update rights are granted joinEnabled#- Is
trueif join rights are granted
Size of revoke requests
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
For NTP synchronization, please ensure that you have configured NTP on your server to keep the clock in sync. This is to prevent system clock drift leading to 400 Invalid Timestamp error response. See Why do I get "Invalid Timestamp" when I grant permissions?.
Other examples
Grant access to list all channel and uuid metadata
The code below allows my-auth-key to list all channel and uuid metadata on the keyset.
1// Allow the auth keys to list all channel and uuid metadata on the keyset.
2// The `get` permission is sent automatically, so no other permission can be set.
3pubnub.grant(
4 authKeys = listOf("my-auth-key"),
5 getAllChannels = true,
6 getAllUUIDs = true
7).async { result ->
8 result.onFailure { exception ->
9 // Handle error
10 }.onSuccess { value ->
11 // Handle successful method result
12 }
13}
Grant subscribe access to a channel only for clients with a specific auth_key with a 5 minute ttl
1pubnub.grant(
2 channels = listOf("my_channel"),
3 write = false,
4 read = true,
5 authKeys = listOf("my_ro_authkey"),
6 ttl = 5
7).async { result -> }
The above code returns the following response to the client:
1if (!status.error) {
2 result!!.ttl // 5
3 result.level // user
4} else {
5 // handle error
6 status.exception?.printStackTrace()
7}
Allow access to a specific channel for Presence
1pubnub.grant(
2 channels = listOf("my_channel-pnpres"),
3 write = true,
4 read = true
5).async { result -> }
Grant Access Manager permissions for channel group
1pubnub.grant(
2 channelGroups = listOf("cg1", "cg2", "cg3"), // groups to allow grant on
3 authKeys = listOf("key1", "key2", "key3"), // the keys we are provisioning
4 write = true, // allow those keys to write (false by default)
5 manage = true, // allow those keys to manage channel groups (false by default)
6 read = true, // allow keys to read the subscribe feed (false by default)
7 ttl = 12337 // how long those keys will remain valid (0 for eternity)
8).async { result -> }
The above code returns the following response to the client:
1if (!status.error) {
2 result!!.ttl // 12337
3 result.level // user
4} else {
5 // handle error
6 status.exception?.printStackTrace()
7}
Application level grant
Use application level grants with caution
When access is granted on an application level, all channels and users will have access.
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.
1pubnub.grant(
2 write = true,
3 read = true
4).async { result -> }
Channel level grant
1pubnub.grant(
2 channels = listOf("my_channel"),
3 write = true,
4 read = true
5).async { result -> }
User level grant
1pubnub.grant(
2 channels = listOf("my_channel"),
3 authKeys = listOf("my_authkey"),
4 write = true,
5 read = true,
6 ttl = 5
7).async { result -> }