Warning: You are viewing an old version (0.8) of this documentation. We recommend you view the latest version 1.2.
API Reference

Authentication

The Auth object is available as the auth fieldAuth propertyauth propertyauth attribute of an Ably Realtime client instance.

Auth Propertiesio.ably.lib.rest.Auth MembersIO.Ably.AblyAuth PropertiesAbly::Auth AttributesARTAuth Properties

The ARTAuth object exposes the following public propertiesattributesmembers:

clientIdclient_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 MethodsIO.Ably.AblyAuth MethodsAbly::Auth MethodsARTAuth Methods

authorizeAuthorize

authorize(TokenParams tokenParams, AuthOptions authOptions, callback(ErrorInfo err, TokenDetails tokenDetails))Deferrable authorize(TokenParams token_params, AuthOptions auth_options) → yields TokenDetailsTokenDetails authorize(TokenParams tokenParams, AuthOptions authOptions)“Task:#token-details AuthorizeAsync(”TokenParams:#token-params?, AuthOptions?)authorize(tokenParams: ARTTokenParams?, authOptions: ARTAuthOptions?, callback: (ARTTokenDetails?, NSError?) → Void)

Ensures valid auth credentials are present for the library instance. This may rely on an already-known and valid token, and will obtain a new token if necessary or explicitly requested using requestTokenrequest_tokenRequestToken..

In the event that a new token request is made, the specified token_params and auth_optionstokenParams and authOptions are used.

The token_params and auth_optionstokenParams and authOptions objects will supplement or override the existing client library defaults, and all subsequent explicit or implicit token requests will use these defaults.

Parameters

token_paramstokenParams
an optional object containing the token parametersan optional TokenParams object containing the token parametersan optional set of key value pairs containing the token parameters for the authorisation request
Type: TokenParams
auth_optionsauthOptions
an optional object containing the authentication optionsan optional TokenParams object containing the authentication optionsan optional set of key value pairs containing the authentication options for the authorisation request
Type: AuthOptions
callback
is a function of the form: function(err, tokenDetails)
&block
yields a TokenDetails object
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

Returns a Task<TokenDetails> 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.

Returns

A Deferrable object is returned from this method.

On success, the registered success callbacks for the Deferrable and any block provided to this method yields a TokenDetails object containing the details of the new or existing token along with the token string.

Failure to obtain a token will trigger the errback callbacks of the Deferrable with an ErrorInfo object containing an error response as defined in the Ably REST API documentation.

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; Error = " + e.Message);
}
client.auth.authorize(client_id: 'bob') do |token_details|
  puts "Success; token = #{token_details.token}"
end
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)")
}
createTokenRequestcreate_token_requestCreateTokenRequestAsync

createTokenRequest(TokenParams tokenParams, AuthOptions authOptions, callback(ErrorInfo err, TokenRequest tokenRequest))Deferrable create_token_request(TokenParams token_params, AuthOptions auth_options) → yields TokenRequestTokenRequest createTokenRequest(TokenParams tokenParams, AuthOptions authOptions)Task<TokenRequest> CreateTokenRequestAsync(TokenParams tokenParams, AuthOptions authOptions)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.

To understand why a token request may be issued to clients in favour 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 set of key value pairs containing the token parameters for the token request
Type: TokenParams
auth_optionsauthOptions
an optional object containing the authentication optionsan optional TokenParams object containing the authentication optionsan optional set of key value pairs containing the authentication optionsan optional ARTTokenParams containing the authentication options
Type: AuthOptions
callback
is a function of the form: function(err, tokenRequest)
&block
yields a TokenRequest object
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

Returns a Task<TokenRequest> which needs to be awaited.

On success, a TokenRequest object is returned.

Failure to issue a TokenRequest will raise an AblyException.

Returns

A Deferrable object is returned from this method.

On success, the registered success callbacks for the Deferrable and any block provided to this method yields a TokenRequest object.

Failure to issue a TokenRequest will trigger the errback callbacks of the Deferrable with an ErrorInfo object containing an error response as defined in the Ably REST API documentation.

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"};
    TokenRequest tokenRequest = await client.Auth.CreateTokenRequestAsync(tokenParams);
    Console.WriteLine("Success; token request issued");
} catch (AblyException e) {
    Console.WriteLine("An error occurred; err = " + e.Message);
}
client.auth.create_token_request(client_id: 'bob') do |token_request|
  puts "Success; token request = #{token_request}"
end
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_tokenRequestTokenAsync

requestToken(TokenParams tokenParams, AuthOptions authOptions, callback(ErrorInfo err, TokenDetails tokenDetails))Deferrable request_token(TokenParams token_params, AuthOptions auth_options) → yields TokenDetailsTokenDetails requestToken(TokenParams tokenParams, AuthOptions authOptions)async Task<TokenDetails> RequestTokenAsync(TokenParams? tokenParams, AuthOptions? options)requestToken(tokenParams: ARTTokenParams?, withOptions: ARTAuthOptions?, callback: (ARTTokenDetails?, NSError?) → Void)

Calls the requestToken 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 they are omitted or null, the default token parameters and authentication options for the client library are used, as specified in the ClientOptions when the client library was instantiated, or later updated with an explicit authorizeAuthorize request.

To understand why a token request may be issued to clients in favour 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 set of key value pairs containing the token parameters for the requested token
Type: TokenParams
auth_optionsauthOptions
an optional object containing the authentication optionsan optional TokenParams object containing the authentication optionsan optional set of key value pairs containing the authentication options for the requested token
Type: AuthOptions
callback
is a function of the form: function(err, tokenDetails)
&block
yields a TokenDetails object
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

Returns a Task<TokenDetails> 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.

Returns

A Deferrable object is returned from this method.

On success, the registered success callbacks for the Deferrable and any block provided to this method yields a TokenDetails object containing the details of the new token along with the token string.

Failure to obtain a token will trigger the errback callbacks of the Deferrable with an ErrorInfo object containing an error response as defined in the Ably REST API documentation.

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);
  }
});
client.auth.request_token(client_id: 'bob') do |token_details|
  puts "Success; token = #{token_details.token}"
end
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"};
  TokenDetails 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 ObjectARTAuthOptionsAuthOptions Hashio.ably.lib.rest.Auth.AuthOptionsIO.Ably.AuthOptions

AuthOptions is a plain JavaScript object and is used when making authentication requests. These options will supplement or override the corresponding options given when the library was instantiated. The following attributes can be defined on the object:

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 instantiated. 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 instantiated. 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 instantiated. 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 instantiated.

PropertiesMembersAttributesAttributes

authCallbackAuthCallbackauth_callback:auth_callback
A functionfunction with the form function(tokenParams, callback(err, tokenOrTokenRequest))TokenCallback instancecallable (eg a lambda)proc / lambda 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: StringUri
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.
Type: ObjectHashAssociative ArrayParam[]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>
forceForce:forceforce
false When true, this indicates to authorizeAuthorize that a new token should be requested, even if the current token is still valid
Type: Boolean
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
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
useTokenAuthUseTokenAuth:use_token_authuse_token_auth
false When true, forces Token authentication to be used by the library. Please note that if a client_idClientIdclientId is not specified in the ClientOptions or TokenParams, then the token issued will be anonymous
Type: Boolean

TokenDetails ObjectARTTokenDetailsio.ably.lib.types.TokenDetailsAbly::Models::TokenDetailsIO.Ably.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 xVLyHw.A-pwh7wenxZ3SkyK3mujn4Qp49vyz4j_RFtbeeVqySJmVIS6Uc
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 canonicalised 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

TokenParams ObjectARTTokenParamsTokenParams Hashio.ably.lib.rest.Auth.TokenParamsIO.Ably.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 instantiated with a key; note that a clientIdclient_idClientId may also be implicit in a token used to instantiate 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.TokenRequestIO.Ably.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: IntegerTimeSpan
timestampTimestamp
The timestamp of this request in milliseconds
Type: IntegerLong IntegerTimeDateTimeOffset
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 canonicalised 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

Need help?

If you need any help with your implementation or if you have encountered any problems, do get in touch. You can also quickly find answers from our knowledge base, and blog.