Please be aware that you are viewing our bleeding edge unstable documentation. Unless you wanted to view the bleeding edge (and possibly unstable) documentation, we recommend you use our stable docs.

Go to Ably's stable canonical documentation »

I know what I'm doing, let me see the bleeding edge docs »

You are viewing our bleeding edge unstable documentation. We recommend you use our stable documentation »
Fork me on GitHub

Authentication

Ably clients can authenticate with Ably using Basic Authentication (which uses the customer’s API key), Token Authentication (which relies on a token customers obtain from Ably), or a token request that customers sign and issue to their clients. Token Authentication, in most cases, is the recommended strategy as it provides robust access control and stringent security measures.

Understanding the Ably authentication schemes

This page of documentation is intended to describe the REST Authentication API and is not intended to explain in depth how Ably’s authentication works. If you are new to Ably and/or the authentication schemes, we strongly recommend that you get acquainted with the following first:

Tutorials

If you’re the kind of person who prefers to dive into code, we have client-server authentication tutorials.

Basic Authentication

Basic Authentication uses one of the api keys configured via the application dashboard as the authentication token. Basic Authentication is the simplest method to use but has some important limitations described in detail in the Basic Authentication documentation.

Here is a straightforward example of using Basic Authentication when instancing a Ably REST client library.

var rest = new Ably.Rest({ key: '{{API_KEY}}' });
var rest = new Ably.Rest({ key: '{{API_KEY}}' });
rest = Ably::Rest.new(key: '{{API_KEY}}')
rest = AblyRest(key='{{API_KEY}}')
$rest = new Ably\AblyRest(array('key' => '{{API_KEY}}'));
ClientOptions options = new ClientOptions();
options.key = "{{API_KEY}}";
AblyRest rest = new AblyRest(options);
var rest = new AblyRest("{{API_KEY}}");
let rest = ARTRest(key: "{{API_KEY}}")
ARTRest *rest = [[ARTRest alloc] initWithKey:@"{{API_KEY}}"];

Token Authentication

Token Authentication uses a token obtained via the REST API requestTokenRequestTokenrequest_token endpoint to authenticate with Ably. Tokens are authentication credentials that are short-lived, and therefore they may more readily be distributed to clients where there is a risk of compromise. Tokens may also be issued with a particular scope – such as a limited set of access rights or capabilities or being limited to use by a specific clientIdClientId identity – and therefore token-based authentication provides the flexibility to implement access and identity control policies in the application. See the Token Authentication documentation for more details.

When using Token Authentication, the REST client library will typically be instanced with a means to obtain a token as opposed to a short-lived token so that when the token expires, the library can assume responsibility to automatically obtain a new token and seamlessly continue operations with Ably. Conversely, if a library is instanced with a previously obtained Token by setting the :token or :token_detailstoken or token_detailsToken or TokenDetailstoken or tokenDetails attributes of ClientOptions, when the token expires, the client will no longer be able successfully issue REST requests to Ably as the library has no means to obtain a new token. It is therefore recommended that all client libraries that use token authentication have a means to issue new tokens using either the auth_url or auth_callbackAuthUrl or AuthCallbackauthUrl or authCallback attribute of ClientOptions when instancing the library.

Below is a rather contrived yet straightforward example that instances a REST library using Token Authentication with a means to reissue tokens as required. Typically, in a browser environment, the authUrlAuthUrl provided would be a relative URL to a local endpoint that is used to issue tokens to trusted clients. Client requests can, for example, be trusted based on session cookies. For non-browser clients, an authentication callback is preferred thus relying on your application to communicate securely with your own servers to obtain a token.

var rest = new Ably.Rest({ authUrl: 'https://my.website/auth' });
var rest = new Ably.Rest({ authUrl: 'https://my.website/auth' });
rest = Ably::Rest.new(auth_url: 'https://my.website/auth')
rest = AblyRest(auth_url='https://my.website/auth')
$rest = new Ably\AblyRest(array('authUrl' => 'https://my.website/auth'));
ClientOptions options = new ClientOptions();
options.authUrl = "https://my.website/auth";
AblyRest rest = new AblyRest(options);
var rest = new AblyRest(new ClientOptions { AuthUrl = new Uri("https://my.website/auth") });
ARTClientOptions *options = [[ARTClientOptions alloc] init];
options.authUrl = [NSURL URLWithString:@"https://my.website/auth"];
ARTRest *rest = [[ARTRest alloc] initWithOptions:options];
let options = ARTClientOptions()
options.authUrl = NSURL(string: "https://my.website/auth")
let rest = ARTRest(options: options)

Auth object

The principal use-case for Auth object is to create signed token request objects or obtain tokens from Ably, and then issue them to other “less trusted” clients. Typically, your servers should be the only devices to have a private API key, and this private API key is used to securely sign token requests or request tokens from Ably. Clients are then issued with short-lived tokens or token requests, and the libraries can then use these to authenticate with Ably. If you adopt this model, your private API key is never shared with clients directly.

A subsidiary use-case for the Auth object is to preemptively trigger renewal of a token or to acquire a new token with a revised set of capabilities by explicitly calling authorizeAuthorize.

Identified clients

When a client has valid credentials to issue requests to Ably, they are considered to be an authenticated client. However, whilst an authenticated client has a verifiable means to authenticate with Ably, they do not necessarily have an identity. When a client is assigned a trusted identity (i.e. a client_idClientIdclientId), then they are considered to be an identified client and for all operations they perform with the Ably service, their client_idClientIdclientId field will be automatically populated and can be trusted by other clients.

For example, assuming you were building a chat application and wanted to allow clients to publish messages on a channel via REST. If each client is assigned a trusted identity by your server, such as a unique email address or UUID, then all other subscribed clients can trust any messages they receive in the channel as being from that client. No other clients are permitted to assume a client_idClientIdclientId that they are not assigned in their token or token request, that is they are unable to masquerade as another client_idClientIdclientId.

In Ably a client can be identified with a client_idClientIdclientId in two ways:

We encourage customers to always issue tokens to clients so that they authenticate using the short-lived token and do not have access to a customer’s private API keys. Since the customer can then control the client_idClientIdclientId that may be used by any of its clients, all other clients can rely on the validity of the client_idClientIdclientId in published messages.

The following example demonstrates how to issue a token with an explicit client_idClientIdclientId that, when used by a client, will then be considered an identified client.

var rest = new Ably.Rest({ key: '{{API_KEY}}' });
rest.auth.createTokenRequest({ clientId: 'Bob' }, function(err, tokenRequest) {
  /* ... issue the TokenRequest to a client ... */
})
var rest = new Ably.Rest({ key: '{{API_KEY}}' });
rest.auth.createTokenRequest({ clientId: 'Bob' }, function(err, tokenRequest) {
  /* ... issue the TokenRequest to a client ... */
})
rest = Ably::Rest.new(key: '{{API_KEY}}')
token_request = rest.auth.create_token_request(client_id: 'Bob')
# ... issue the TokenRequest to a client ...
rest = AblyRest(key='{{API_KEY}}')
token_request = rest.auth.create_token_request(client_id='Bob')
# ... issue the TokenRequest to a client ...
$rest = new Ably\AblyRest(array('key' => '{{API_KEY}}'));
$tokenRequest = $rest->auth->createTokenRequest(array('clientId' => 'Bob'));
# ... issue the TokenRequest to a client ...
ClientOptions options = new ClientOptions();
options.key = "{{API_KEY}}";
AblyRest rest = new AblyRest(options);
TokenParams tokenParams = new TokenParams();
tokenParams.clientId = "Bob";
TokenRequest tokenRequest;
tokenRequest = rest.auth.createTokenRequest(tokenParams, null);
/* ... issue the TokenRequest to a client ... */
var rest = new AblyRest(new ClientOptions {Key = "{{API_KEY}}"});
var tokenParams = new TokenParams {ClientId = "Bob"};
TokenRequest tokenRequest = await rest.Auth.CreateTokenRequestAsync(tokenParams);
// ... issue the TokenRequest to a client ...
ARTRest *rest = [[ARTRest alloc] initWithKey:@"{{API_KEY}}"];
ARTTokenParams *tokenParams = [[ARTTokenParams alloc] initWithClientId:@"Bob"];
[rest.auth createTokenRequest:tokenParams options:nil
  callback:^(ARTTokenRequest *tokenRequest, NSError *error) {
    // ... issue the TokenRequest to a client ...
}];
let rest = ARTRest(key: "{{API_KEY}}")
let tokenParams = ARTTokenParams(clientId: "Bob")
rest.auth.createTokenRequest(tokenParams, options: nil) { tokenRequest, error in
  // ... issue the TokenRequest to a client ...
}

Auth API Reference

The Auth object is available as the auth fieldauth propertyAuth propertyauth attribute of an Ably REST client instance.

Auth PropertiesAbly\Auth Propertiesio.ably.lib.rest.Auth MembersAbly::Auth AttributesAuth AttributesARTAuth Properties

The ARTAuth object exposes the following public propertiesattributesmembers:

clientIdclient_idclient_idClientId

The client ID string, if any, configured for this client connection. See identified clients for more information on trusted client identifiers.

Auth Methodsio.ably.lib.rest.Auth MethodsAbly::Auth MethodsAbly\Auth MethodsARTAuth Methods

authorizeAuthorize

authorize(TokenParams tokenParams, AuthOptions authOptions, callback(ErrorInfo err, TokenDetails tokenDetails))TokenDetails authorize(TokenParams token_params, AuthOptions auth_options)TokenDetails authorize(token_params=TokenParams, auth_options=AuthOptions)TokenDetails authorize(TokenParams tokenParams, AuthOptions authOptions)TokenDetails authorize(TokenParams tokenParams, AuthOptions authOptions)Task AuthorizeAsync(TokenParams tokenParams = null, AuthOptions options = null);authorize(tokenParams: ARTTokenParams?, authOptions: ARTAuthOptions?, callback: (ARTTokenDetails?, NSError?) → Void)

Instructs the library to get a new token immediately using the specified token_params and auth_optionstokenParams and authOptions (or if none specified, the client library defaults). Also stores any token_params and auth_optionstokenParams and authOptions passed in as the new defaults, to be used for all subsequent implicit or explicit token requests.

Any token_params and auth_optionstokenParams and authOptions objects passed in will entirely replace (as opposed to being merged with) the currently saved token_params and auth_optionstokenParams and authOptions.

Parameters

token_paramstokenParams
an optional object containing the token parametersan optional TokenParams object containing the token parametersan optional Dict containing the token parametersan optional set of key value pairs containing the token parametersan optional set of key value pairs in an associative array containing the token parameters for the authorization request
Type: TokenParams
auth_optionsauthOptions
an optional object containing the authentication optionsan optional AuthOptions object containing the authentication optionsan optional Dict containing the authentication optionsan optional set of key value pairs containing the authentication optionsan optional set of key value pairs in an associative array containing the authentication options for the authorization request
Type: AuthOptions
callback
is a function of the form: function(err, tokenDetails)
callback
called with a ARTTokenDetails object or an error

Callback result

On success, tokenDetails contains a TokenDetails object containing the details of the new or existing token along with the token string.

On failure to obtain a token, err contains an ErrorInfoNSError object with an error response as defined in the Ably REST API documentation.

Returns

On success, a TokenDetails object containing the details of the new or existing token along with the token string is returned.

Failure to obtain a token will raise an AblyException.

Returns

The method is asynchronous and returns a Task which needs to be awaited.

On success, a TokenDetails object containing the details of the new or existing token along with the token string is returned.

Failure to obtain a token will raise an AblyException.

Example

client.auth.authorize({ clientId: 'bob' }, function(err, tokenDetails) {
  if(err) {
    console.log('An error occurred; err = ' + err.message);
  } else {
    console.log('Success; token = ' + tokenDetails.token);
  }
});
client.auth.authorize({ clientId: 'bob' }, function(err, tokenDetails) {
  if(err) {
    console.log('An error occurred; err = ' + err.message);
  } else {
    console.log('Success; token = ' + tokenDetails.token);
  }
});
try {
  TokenParams tokenParams = new TokenParams();
  tokenParams.clientId = "bob";
  TokenDetails tokenDetails = client.auth.authorize(tokenParams, null);
  System.out.println("Success; token = " + tokenDetails.token);
} catch(AblyException e) {
  System.out.println("An error occurred; err = " + e.getMessage());
}
try
{
  TokenParams tokenParams = new TokenParams { ClientId = "bob" };
  TokenDetails tokenDetails = await client.Auth.AuthorizeAsync(tokenParams);
  Console.WriteLine("Success; token = " + tokenDetails.Token);
}
catch (AblyException e)
{
  Console.WriteLine("An error occurred; err = " + e.Message);
}
token_details = client.auth.authorize(client_id: 'bob')
puts "Success; token = #{token_details.token}"
token_details = client.auth.authorize(token_params={'client_id': 'bob'})
print("Success; token = " + str(token_details.token))
$tokenDetails = $client->auth->authorize(array('clientId' => 'bob'));
echo("Success; token = " . $tokenDetails->token);
ARTTokenParams *tokenParams = [[ARTTokenParams alloc] initWithClientId:@"Bob"];
[client.auth authorize:tokenParams options:nil callback:^(ARTTokenDetails *tokenDetails, NSError *error) {
  if (error) {
    NSLog(@"An error occurred; err = %@", error);
  } else {
    NSLog(@"Success; token = %@", tokenDetails.token);
  }
}];
let tokenParams = ARTTokenParams(clientId: "Bob")
client.auth.authorize(tokenParams, options: nil) { tokenDetails, error in
  guard let tokenDetails = tokenDetails else {
    print("An error occurred; err = \(error!)")
    return
  }
  print("Success; token = \(tokenDetails.token)")
}
createTokenRequestCreateTokenRequestcreate_token_requestcreate_token_request

createTokenRequest(TokenParams tokenParams, AuthOptions authOptions, callback(ErrorInfo err, TokenRequest tokenRequest))TokenRequest create_token_request(TokenParams token_params, AuthOptions auth_options)TokenRequest create_token_request(token_params=TokenParams, key_name=String, key_secret=String)TokenRequest createTokenRequest(TokenParams tokenParams, AuthOptions authOptions)TokenRequest createTokenRequest(TokenParams tokenParams, AuthOptions authOptions)Task CreateTokenRequestAsync(TokenParams tokenParams = null, AuthOptions authOptions = null)createTokenRequest(tokenParams: ARTTokenParams?, options: ARTAuthOptions?, callback: (ARTTokenRequest?, NSError?) → Void)

Creates and signs a token request based on the specified token_params and auth_optionstokenParams and authOptions. Note this can only be used when the API key value is available locally. Otherwise, signed token requests must be obtained from the key owner. Use this to generate signed token requests in order to implement a token request callback for use by other clients.

Both auth_options and token_paramsauthOptions and tokenParams are optional. When omitted or nullNullNonenil, the default token parameters and authentication options for the client library are used, as specified in the ClientOptions when the client library was instanced, or later updated with an explicit authorizeAuthorize request. Values passed in will be used instead of (rather than being merged with) the default values.

To understand why a token request may be issued to clients in favor of a token, see Token Authentication explained.

Parameters

token_paramstokenParams
an optional object containing the token parametersan optional TokenParams object containing the token parametersan optional Dict containing the token parametersan optional set of key value pairs containing the token parametersan optional set of key value pairs in an associative array containing the token parameters for the token request
Type: TokenParams
auth_options[auth options]authOptions
an optional object containing the authentication optionsan optional TokenParams object containing the authentication optionsvarious keyword arguments with the authentication optionsan optional set of key value pairs containing the authentication optionsan optional set of key value pairs in an associative array containing the authentication optionsan optional ARTTokenParams containing the authentication options for the token request
Type: AuthOptions
callback
is a function of the form: function(err, tokenRequest)
callback
called with a ARTTokenRequest object or an error

Callback result

On success, tokenRequest contains a TokenRequest JSON object.

On failure to issue a TokenRequest, err contains an ErrorInfo object with an error response as defined in the Ably REST API documentation.

Returns

On success, a TokenRequest object is returned.

Failure to issue a TokenRequest will raise an AblyException.

Returns

The method is asynchronous and returns a Task which needs to be awaited.

On success, a TokenRequest object is returned.

Failure to issue a TokenRequest will raise an AblyException.

Example

client.auth.createTokenRequest({ clientId: 'bob' }, function(err, tokenRequest) {
  if(err) {
    console.log('An error occurred; err = ' + err.message);
  } else {
    console.log('Success; token request = ' + tokenRequest);
  }
});
client.auth.createTokenRequest({ clientId: 'bob' }, function(err, tokenRequest) {
  if(err) {
    console.log('An error occurred; err = ' + err.message);
  } else {
    console.log('Success; token request = ' + tokenRequest);
  }
});
try {
  TokenParams tokenParams = new TokenParams();
  tokenParams.clientId = "bob";
  TokenRequest tokenRequest = client.auth.createTokenRequest(tokenParams, null);
  System.out.println("Success; token request issued");
} catch(AblyException e) {
  System.out.println("An error occurred; err = " + e.getMessage());
}
try
{
  TokenParams tokenParams = new TokenParams { ClientId = "bob" };
  var tokenRequest = await client.Auth.CreateTokenRequestAsync(tokenParams);
  Console.WriteLine("Success; token request issued");
}
catch (AblyException e)
{
  Console.WriteLine("An error occurred; err = " + e.Message);
}
token_request = client.auth.create_token_request(client_id: 'bob')
puts "Success; token request = #{token_request}"
token_request = client.auth.create_token_request(token_params={'client_id': 'bob'})
print("Success; token request = ' + str(token_request)
$tokenRequest = $client->auth->createTokenRequest(array('clientId' => 'bob'))
echo("Success; token request = " . $tokenRequest);
ARTTokenParams *tokenParams = [[ARTTokenParams alloc] initWithClientId:@"Bob"];
[client.auth createTokenRequest:tokenParams options:nil callback:^(ARTTokenRequest *tokenRequest, NSError *error) {
    if (error) {
        NSLog(@"An error occurred; err = %@", error);
    } else {
        NSLog(@"Success; token request = %@", tokenRequest);
    }
}];
let tokenParams = ARTTokenParams(clientId: "Bob")
client.auth.createTokenRequest(tokenParams, options: nil) { tokenRequest, error in
    guard let tokenRequest = tokenRequest else {
        print("An error occurred; err = \(error!)")
        return
    }
    print("Success; token request = \(tokenRequest)")
}
requestTokenrequest_tokenrequest_tokenRequestToken

requestToken(TokenParams tokenParams, AuthOptions authOptions, callback(ErrorInfo err, TokenDetails tokenDetails))TokenDetails request_token(TokenParams token_params, AuthOptions auth_options)TokenDetails request_token(token_params=TokenParams, key_name=String, key_secret=None, auth_callback=Lambda, auth_url=String, auth_method=String, auth_headers=Dict, auth_params=Dict, query_time=Boolean)TokenDetails requestToken(TokenParams tokenParams, AuthOptions authAptions)Task RequestTokenAsync(TokenParams tokenParams = null, AuthOptions options = null)TokenDetails requestToken(TokenParams tokenParams, AuthOptions authOptions)requestToken(tokenParams: ARTTokenParams?, withOptions: ARTAuthOptions?, callback: (ARTTokenDetails?, NSError?) → Void)

Calls the requestTokenRequestToken REST API endpoint to obtain a token according to the specified token_params and auth_optionstokenParams and authOptions.

Both auth_options and token_paramsauthOptions and tokenParams are optional. When omitted or nullNullNonenil, the default token parameters and authentication options for the client library are used, as specified in the ClientOptions when the client library was instanced, or later updated with an explicit authorizeAuthorize request. Values passed in will be used instead of (rather than being merged with) the default values.

To understand why a token request may be issued to clients in favor of a token, see Token Authentication explained.

Parameters

token_paramstokenParams
an optional object containing the token parametersan optional Dict containing the token parametersan optional TokenParams object containing the token parametersan optional set of key value pairs containing the token parametersan optional set of key value pairs in an associative array containing the token parameters for the requested token
Type: TokenParams
[auth options]auth_optionsauthOptions
an optional object containing the authentication optionsvarious keyword arguments with the authentication optionsan optional TokenParams object containing the authentication optionsan optional set of key value pairs containing the authentication optionsan optional set of key value pairs in an associative array containing the authentication options for the requested token
Type: AuthOptions
callback
is a function of the form: function(err, tokenDetails)
callback
called with a ARTTokenDetails object or an error

Callback result

On success, tokenDetails contains a TokenDetails object containing the details of the new token along with the token string.

On failure to obtain a token, err contains an ErrorInfoNSError object with an error response as defined in the Ably REST API documentation.

Returns

On success, a TokenDetails object containing the details of the new token along with the token string is returned.

Failure to obtain a token will raise an AblyException.

Returns

The method is asynchronous and returns a Task which needs to be awaited.

On success, a TokenDetails object containing the details of the new token along with the token string is returned.

Failure to obtain a token will raise an AblyException.

Example

client.auth.requestToken({ clientId: 'bob'}, function(err, tokenDetails){
  if(err) {
    console.log('An error occurred; err = ' + err.message);
  } else {
    console.log('Success; token = ' + tokenDetails.token);
  }
});
client.auth.requestToken({ clientId: 'bob'}, function(err, tokenDetails){
  if(err) {
    console.log('An error occurred; err = ' + err.message);
  } else {
    console.log('Success; token = ' + tokenDetails.token);
  }
});
token_details = client.auth.request_token(client_id: 'bob')
puts "Success; token = #{token_details.token}"
token_details = client.auth.request_token(token_params={'client_id': 'bob'})
print("Success; token = " + str(token_details.token))
$tokenDetails = $client->auth->requestToken(array('clientId' => 'bob'))
echo("Success; token = " . $tokenDetails->token);
try {
  TokenParams tokenParams = new TokenParams();
  tokenParams.clientId = "bob";
  TokenDetails tokenDetails = client.auth.requestToken(tokenParams, null);
  System.out.println("Success; token = " + tokenDetails.token);
} catch(AblyException e) {
  System.out.println("An error occurred; err = " + e.getMessage());
}
try {
  TokenParams tokenParams = new TokenParams { ClientId = "bob" };
  var tokenDetails = await client.Auth.RequestTokenAsync(tokenParams);
  Console.WriteLine("Success; token = " + tokenDetails.Token);
}
catch (AblyException e)
{
  Console.WriteLine("An error occurred; err = " + e.Message);
}
ARTTokenParams *tokenParams = [[ARTTokenParams alloc] initWithClientId:@"Bob"];
[client.auth requestToken:tokenParams withOptions:nil callback:^(ARTTokenDetails *tokenDetails, NSError *error) {
    if (error) {
        NSLog(@"An error occurred; err = %@", error);
    } else {
        NSLog(@"Success; token = %@", tokenDetails.token);
    }
}];
let tokenParams = ARTTokenParams(clientId: "Bob")
client.auth.requestToken(tokenParams, withOptions: nil) { tokenDetails, error in
    guard let tokenDetails = tokenDetails else {
        print("An error occurred; err = \(error!)")
        return
    }
    print("Success; token = \(tokenDetails.token)")
}

AuthOptions ObjectAuthOptions Hashio.ably.lib.rest.Auth.AuthOptions

AuthOptions is a plain Javascript object and is used when making authentication requests. If passed in, an authOptions object will be used instead of (as opposed to supplementing or being merged with) the default values given when the library was instanced. The following attributes are supported:

AuthOptions is a Hash object and is used when making authentication requests. These options will supplement or override the corresponding options given when the library was instanced. The following key symbol values can be added to the Hash:

AuthOptions is a Dict and is used when making authentication requests. These options will supplement or override the corresponding options given when the library was instanced. The following key symbol values can be added to the Dict:

AuthOptions is an Associative Array and is used when making authentication requests. These options will supplement or override the corresponding options given when the library was instanced. The following named keys and values can be added to the Associative Array:

ARTAuthOptions is used when making authentication requests. These options will supplement or override the corresponding options given when the library was instanced.

PropertiesMembersAttributesAttributes

authCallbackAuthCallbackauth_callback:auth_callback
A functionfunction with the form function(tokenParams, callback(err, tokenOrTokenRequest))TokenCallback instancecallable (eg a lambda)proc / lambda (called synchronously in REST and Realtime but does not block EventMachine in the latter) which is called when a new token is required. The role of the callback is to either generate a signed TokenRequest which may then be submitted automatically by the library to the Ably REST API requestToken; or to provide a valid token in as a TokenDetails object. See an authentication callback example or our authentication documentation for details of the token request format and associated API calls.
Type: CallableTokenCallbackProcFunc<TokenParams, Task<TokenDetails>>
authUrlAuthUrl:auth_urlauth_url
A URL that the library may use to obtain a token string (in plain text format), or a signed TokenRequest or TokenDetails (in JSON format). For example, this can be used by a client to obtain signed token requests from an application server.
Type: StringUriNSURL
authMethodAuthMethod:auth_methodauth_method
GET:get The HTTP verb to use for the request, either GET:get or POST:post
Type: StringSymbolHttpMethod
authHeadersAuthHeaders:auth_headersauth_headers
A set of key value pair headers to be added to any request made to the authUrlAuthUrl. Useful when an application requires these to be added to validate the request or implement the response. If the authHeaders object contains an authorization key, then withCredentials will be set on the xhr request.
Type: ObjectHashAssociative ArrayParam[]Dictionary<string, string>NSDictionary<String *, String *>[String, String]/Dictionary<String, String>
authParamsAuthParams:auth_paramsauth_params
A set of key value pair params to be added to any request made to the authUrlAuthUrl. When the authMethodAuthMethod is GET, query params are added to the URL, whereas when authMethodAuthMethod is POST, the params are sent as URL encoded form data. Useful when an application require these to be added to validate the request or implement the response.
Type: ObjectHashAssociative ArrayParam[]Dictionary<string, string>NSArray<NSURLQueryItem *>[NSURLQueryItem]/Array<NSURLQueryItem>
keyKey:keykey
Optionally the API key to use can be specified as a full key string; if not, the API key passed into ClientOptions when instancing the Realtime or REST library is used
Type: String
queryTimeQueryTime:query_timequery_time
false If true, the library will query the Ably servers for the current time instead of relying on a locally-available time of day. Knowing the time accurately is needed to create valid signed token requests, so this option is useful for library instances on auth servers if the server clock is insufficiently accurate. The server is queried only once per client library instance, and used to calculate and store the offset from the local clock.
Type: Boolean
tokenToken:tokentoken
An authenticated token string that is most commonly obtained from the tokenToken property of a TokenDetails component of a token request response. Use this option if you wish to use Token authentication. Read more about Token authentication
Type: String
tokenDetailsTokenDetails:token_detailstoken_details
An authenticated TokenDetails object that is most commonly obtained from of a token request response. Use this option if you wish to use Token authentication. Read more about Token authentication
Type: TokenDetails

TokenDetailsARTTokenDetailsio.ably.lib.types.TokenDetailsAbly::Models::TokenDetails

TokenDetails is a type providing details of the token string and its associated metadata.

PropertiesMembersAttributes

tokenToken
The token itself. A typical token string may appear like {{TOKEN}}
Type: String
expiresExpires
The time (in milliseconds since the epoch)The time at which this token expires
Type: IntegerLong IntegerDateTimeOffsetTimeNSDate
issuedIssued
The time (in milliseconds since the epoch)The time at which this token was issued
Type: IntegerLong IntegerDateTimeOffsetTimeNSDate
capabilityCapability
The capability associated with this token. The capability is a a JSON stringified canonicalized representation of the resource paths and associated operations. Read more about authentication and capabilities
Type: StringCapability
clientIdclient_idClientId
The client ID, if any, bound to this token. If a client ID is included, then the token authenticates its bearer as that client ID, and the token may only be used to perform operations on behalf of that client ID. The client is then considered to be an identified client
Type: String

Methods

expired?
True when the token has expired
Type: Boolean

Methods

is_expired()
True when the token has expired
Type: Boolean

Methods

IsValidToken()
True if the token has not expired
Type: Boolean

TokenDetails constructors

TokenDetails.fromJsonTokenDetails.from_json

TokenDetails.fromJson(String json) → TokenDetailsTokenDetails.from_json(String json) → TokenDetails

TokenDetails.fromJson(Object json) → TokenDetailsTokenDetails.from_json(Object json) → TokenDetails

A static factory method to create a TokenDetails from a deserialized TokenDetails-like object or a JSON stringified TokenDetails. This method is provided to minimize bugs as a result of differing types by platform for fields such as timestamp or ttl. For example, in Ruby ttl in the TokenDetails object is exposed in seconds as that is idiomatic for the language, yet when serialized to JSON using to_json it is automatically converted to the Ably standard which is milliseconds. By using the fromJson method when constructing a TokenDetails, Ably ensures that all fields are consistently serialized and deserialized across platforms.

Parameters

json
a TokenDetails-like deserialized object or JSON stringified TokenDetails.
Type: Object, String

Returns

A TokenDetails object

TokenParams ObjectARTTokenParamsTokenParams Hashio.ably.lib.rest.Auth.TokenParams

TokenParams is a plain Javascript object and is used in the parameters of token authentication requests, corresponding to the desired attributes of the token. The following attributes can be defined on the object:

TokenParams is a Hash object and is used in the parameters of token authentication requests, corresponding to the desired attributes of the token. The following key symbol values can be added to the Hash:

TokenParams is a Dict and is used in the parameters of token authentication requests, corresponding to the desired attributes of the token. The following keys-value pairs can be added to the Dict:

TokenParams is an Associative Array and is used in the parameters of token authentication requests, corresponding to the desired attributes of the token. The following named keys and values can be added to the Associative Array:

TokenParams is used in the parameters of token authentication requests, corresponding to the desired attributes of the token.

ARTTokenParams is used in the parameters of token authentication requests, corresponding to the desired attributes of the token.

PropertiesMembersAttributesAttributes

capabilityCapability:capability
JSON stringified capability of the token. If the token request is successful, the capability of the returned token will be the intersection of this capability with the capability of the issuing key. Find our more about how to use capabilities to manage access privileges for clients. Type: StringCapability
clientIdClientIdclient_id:client_id
A client ID, used for identifying this client when publishing messages or for presence purposes. The clientIdclient_idClientId can be any non-empty string. This option is primarily intended to be used in situations where the library is instanced with a key; note that a clientIdclient_idClientId may also be implicit in a token used to instance the library; an error will be raised if a clientIdclient_idClientId specified here conflicts with the clientIdclient_idClientId implicit in the token. Find out more about client identities
Type: String
nonceNonce:nonce
An optional opaque nonce string of at least 16 characters to ensure uniqueness of this request. Any subsequent request using the same nonce will be rejected.
Type: String
timestamptimestamp:timestamp
The timestamp (in milliseconds since the epoch)The timestamp of this request. timestamp, in conjunction with the nonce, is used to prevent token requests from being replayed.
Type: IntegerLong IntegerTimeNSDateDateTimeOffset
ttlTtl:ttl
1 hour Requested time to live for the token being created in millisecondsin secondsas a NSTimeIntervalas a TimeSpan. When omitted, the Ably REST API default of 60 minutes is applied by Ably
Type: Integer (milliseconds)Integer (seconds)NSTimeIntervalLong IntegerTimeSpan

TokenRequest ObjectARTTokenRequestAbly::Models::TokenRequestio.ably.lib.rest.Auth.TokenRequest

TokenRequest is a type containing parameters for a token request. Tokens are requested using Auth#requestTokenAuth#request_token

PropertiesMembersAttributes

keyNamekey_nameKeyName
The key name of the key against which this request is made. The key name is public, whereas the key secret is private
Type: String
ttlTtl
Requested time to live for the token in millisecondsin secondsas a TimeSpan. If the token request is successful, the TTL of the returned token will be less than or equal to this value depending on application settings and the attributes of the issuing key.
Type: IntegerTimeSpanNSTimeInterval
timestampTimestamp
The timestamp of this request in milliseconds
Type: IntegerLong IntegerTimeDateTimeOffsetNSDate
capabilityCapability
Capability of the token. If the token request is successful, the capability of the returned token will be the intersection of this capability with the capability of the issuing key. The capability is a a JSON stringified canonicalized representation of the resource paths and associated operations. Read more about authentication and capabilities
Type: String
clientIdclient_idClientId
The client ID to associate with this token. When provided, the token may only be used to perform operations on behalf of that client ID
Type: String
nonceNonce
An opaque nonce string of at least 16 characters
Type: String
macMac
The Message Authentication Code for this request
Type: String

TokenRequest constructors

TokenRequest.fromJsonTokenRequest.from_json

TokenRequest.fromJson(String json) → TokenRequestTokenRequest.from_json(String json) → TokenRequest

TokenRequest.fromJson(Object json) → TokenRequestTokenRequest.from_json(Object json) → TokenRequest

A static factory method to create a TokenRequest from a deserialized TokenRequest-like object or a JSON stringified TokenRequest. This method is provided to minimize bugs as a result of differing types by platform for fields such as timestamp or ttl. For example, in Ruby ttl in the TokenRequest object is exposed in seconds as that is idiomatic for the language, yet when serialized to JSON using to_json it is automatically converted to the Ably standard which is milliseconds. By using the fromJson method when constructing a TokenRequest, Ably ensures that all fields are consistently serialized and deserialized across platforms.

Parameters

json
a TokenRequest-like deserialized object or JSON stringified TokenRequest.
Type: Object, String

Returns

A TokenRequest object


Back to top