Authentication
This is the Authentication API Reference.
Tokens
In the documentation, references to Ably-compatible tokens typically refer either to an Ably Token, or an Ably JWT. For Ably Tokens, this can either be referring to the TokenDetails
object that contain the token
string or the token string itself. TokenDetails
objects are obtained when requesting an Ably Token from the Ably service and contain not only the token
string in the token
attribute, but also contain attributes describing the properties of the Ably Token. For Ably JWT, this will be simply referring to a JWT which has been signed by an Ably private API key.
Auth object
The principal use-case for the Auth
object is to create Ably TokenRequest
objects with createTokenRequest or obtain Ably Tokens from Ably with requestToken, 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 Ably TokenRequest
objects or request Ably Tokens from Ably. Clients are then issued with these short-lived Ably Tokens or Ably TokenRequest
objects, 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 authorize
Authorize
.
- Properties
- Methods
- Related types
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 ART
Auth
object exposes the following public propertiesattributesmembers:
clientIdclient_idclient_idClientIdClientID
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); TokenDetails Authorize(TokenParams tokenParams, AuthOptions authOptions)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_options
tokenParams
and authOptions
TokenParams
and AuthOptions
(or if none specified, the client library defaults). Also stores any token_params
and auth_options
TokenParams
and AuthOptions
tokenParams
and authOptions
passed in as the new defaults, to be used for all subsequent implicit or explicit token requests.
Any token_params
and auth_options
TokenParams
and AuthOptions
tokenParams
and authOptions
objects passed in will entirely replace (as opposed to being merged with) the currently saved token_params
and auth_options
tokenParams
and authOptions
.
Parameters
- token_paramsTokenParamstokenParams
-
an optional object containing the Ably Token parametersan optional
TokenParams
object containing the token parametersan optional Dict containing the Ably Token parametersan optional set of key value pairs containing the Ably Token parametersan optional set of key value pairs in an associative array containing the Ably Token parameters for the authorization request
Type:TokenParams
- auth_optionsAuthOptionsauthOptions
-
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 Ably Token along with the token
string.
On failure to obtain an token, err
contains an ErrorInfo
NSError
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 an 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)")
}
tokenParams := &ably.TokenParams{
ClientID: "Bob",
}
token, err := client.Auth.Authorize(tokenParams, &ably.AuthOptions{})
if err != nil {
fmt.Println(err)
}
fmt.Println(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)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 an Ably TokenRequest
based on the specified token_params
and auth_options
TokenParams
and AuthOptions
tokenParams
and authOptions
. Note this can only be used when the API key
value is available locally, due to it being required to sign the Ably TokenRequest
. Otherwise, Ably TokenRequests
must be obtained from the key owner. Use this to generate Ably TokenRequests
in order to implement an Ably Token request callback for use by other clients.
Both auth_options
and token_params
AuthOptions
and TokenParams
authOptions
and tokenParams
are optional. When omitted or null
Null
None
nil
, the default Ably-compatible 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 authorize
Authorize
request. Values passed in will be used instead of (rather than being merged with) the default values.
To understand why an Ably TokenRequest
may be issued to clients in favor of an Ably Token, see Token Authentication explained.
Parameters
- token_paramsTokenParamstokenParams
-
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 AblyTokenRequest
Type:TokenParams
- auth_options[auth options]AuthOptionsauthOptions
-
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 optionalARTTokenParams
containing the authentication options for the Ably 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)")
}
tokenParams := &ably.TokenParams{
ClientID: "Bob",
}
tokenRequest, err := client.Auth.CreateTokenRequest(tokenParams, &ably.AuthOptions{})
if err != nil {
fmt.Println(err)
}
fmt.Println(tokenRequest)
requestTokenrequest_tokenrequest_tokenRequestTokenRequestToken
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 authOptions)Task
RequestTokenAsync(TokenParams tokenParams = null, AuthOptions options = null) TokenDetails requestToken(TokenParams tokenParams, AuthOptions authOptions)requestToken(tokenParams: ARTTokenParams?, withOptions: ARTAuthOptions?, callback: (ARTTokenDetails?, NSError?) → Void)TokenDetails RequestToken(TokenParams tokenParams, AuthOptions authOptions)
Calls the requestToken
RequestToken
REST API endpoint to obtain an Ably Token according to the specified token_params
and auth_options
tokenParams
and authOptions
.
Both auth_options
and token_params
authOptions
and tokenParams
are optional. When omitted or null
Null
None
nil
, 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 authorize
Authorize
request. Values passed in will be used instead of (rather than being merged with) the default values.
To understand why an Ably TokenRequest
may be issued to clients in favor of an Ably 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 Ably 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 Ably 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 Ably Token along with the token
string.
On failure to obtain an Ably Token, err
contains an ErrorInfo
NSError
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 Ably Token along with the token
string is returned.
Failure to obtain an Ably 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 Ably Token along with the token
string is returned.
Failure to obtain an Ably 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)")
}
tokenParams := &ably.TokenParams{
ClientID: "Bob",
}
token, err := client.Auth.RequestToken(tokenParams, &ably.AuthOptions{})
if err != nil {
fmt.Println(err)
}
fmt.Println(token)
Related types
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 instantiated. 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 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:
ART
AuthOptions
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 (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 obtain a fresh token, one of: an Ably Token string (in plain text format); a signedTokenRequest
; aTokenDetails
(in JSON format); an Ably JWT. See an authentication callback example or our authentication documentation for details of the Ably TokenRequest format and associated API calls.
Type:Callable
TokenCallback
Proc
Func<TokenParams, Task<TokenDetails>>
- authUrlAuthUrl:auth_urlauth_url
- A URL that the library may use to obtain a fresh token, one of: an Ably Token string (in plain text format); a signed
TokenRequest
; aTokenDetails
(in JSON format); an Ably JWT. For example, this can be used by a client to obtain signed Ably TokenRequests from an application server.
Type:String
Uri
NSURL
- authMethodAuthMethodauth_method:auth_method
-
GET
:get
The HTTP verb to use for the request, eitherGET
:get
orPOST
:post
Type:String
Symbol
HttpMethod
- authHeadersAuthHeadersauth_headers:auth_headers
- A set of key value pair headers to be added to any request made to the
authUrl
AuthUrl
. Useful when an application requires these to be added to validate the request or implement the response. If theauthHeaders
object contains anauthorization
key, thenwithCredentials
will be set on the xhr request.
Type:Object
Dict
Hash
Associative Array
Param []
Dictionary<string, string>
Map<String, String>
- authParamsAuthParams:auth_paramsauth_params
- A set of key value pair params to be added to any request made to the
authUrl
AuthUrl
. When theauthMethod
AuthMethod
isGET
, query params are added to the URL, whereas whenauthMethod
AuthMethod
isPOST
, 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:Object
Hash
Associative Array
Param[]
Dictionary<string, string>
NSArray<NSURLQueryItem *>
[NSURLQueryItem]/Array<NSURLQueryItem>
Map<String, String>
- tokenDetailsTokenDetailstoken_details:token_details
- An authenticated
TokenDetails
object (most commonly obtained from an Ably Token Request response). This option is mostly useful for testing: since tokens are short-lived, in production you almost always want to use an authentication method that allows the client library to renew the token automatically when the previous one expires, such asauthUrl
AuthUrl
:auth_url
auth_url
orauthCallback
AuthCallbackauth_callback
:auth_callback
. Use this option if you wish to use Token authentication. Read more about Token authentication
Type:TokenDetails
- 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 when issuing TokenRequests instead of relying on a locally-available time of day. Knowing the time accurately is needed to create valid signed Ably TokenRequests, so this option is useful for library instances on auth servers where for some reason the server clock cannot be kept synchronized through normal means, such as an NTP daemon . The server is queried for the current time once per client library instance (which stores the offset from the local clock), so if using this option you should avoid instancing a new version of the library for each request.
Type:Boolean
- tokenToken:token
- An authenticated token. This can either be a
TokenDetails
object, aTokenRequest
object, or token string (obtained from thetoken
Token
property of aTokenDetails
component of an Ably TokenRequest response, or a JSON Web Token satisfying the Ably requirements for JWTs). This option is mostly useful for testing: since tokens are short-lived, in production you almost always want to use an authentication method that allows the client library to renew the token automatically when the previous one expires, such asauthUrl
AuthUrl:auth_urlauth_url or authCallbackAuthCallbackauth_callback:auth_callback. Read more about Token authentication
Type:String
,TokenDetails
orTokenRequest
TokenDetailsARTTokenDetailsio.ably.lib.types.TokenDetailsAbly::Models::TokenDetails
TokenDetails
is a type providing details of Ably Token string and its associated metadata.
PropertiesMembersAttributes
- tokenToken
- The Ably Token itself. A typical Ably Token string may appear like
xVLyHw.A-pwh7w-SauV8CriBYaKE96As7U9CdwyfjFnAdzMOk-26EcFz4
Type:String
- expiresExpires
-
The time (in milliseconds since the epoch)The time at which this token expires
Type:Integer
Long Integer
DateTimeOffset
Time
NSDate
- issuedIssued
-
The time (in milliseconds since the epoch)The time at which this token was issued
Type:Integer
Long Integer
DateTimeOffset
Time
NSDate
- capabilityCapability
- The capability associated with this Ably Token. The capability is a a JSON stringified canonicalized representation of the resource paths and associated operations. Read more about authentication and capabilities
Type:String
Capability
- clientIdclient_idClientId
- The client ID, if any, bound to this Ably Token. If a client ID is included, then the Ably Token authenticates its bearer as that client ID, and the Ably 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_jsonTokenDetails.fromMap
TokenDetails.fromJson(String json) → TokenDetailsTokenDetails.from_json(String json) → TokenDetailsTokenDetails.fromMap(Map<String, dynamic> map)
A static factory methodnamed constructor to create a TokenDetails
from a deserialized TokenDetails
-like object or a JSON stringified TokenDetails
map. 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
fromMap
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 stringifiedTokenDetails
.
Type:Object, String
- map
- a
TokenDetails
-like deserialized map.
Type:Map<String, dynamic>
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 Ably 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 Ably 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 Ably 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 Ably 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 Ably Token.
ARTTokenParams
is used in the parameters of token authentication requests, corresponding to the desired attributes of the Ably Token.
PropertiesMembersAttributesAttributes
- capabilityCapability:capability
-
JSON stringified capability of the Ably Token. If the Ably Token request is successful, the capability of the returned Ably 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:
String
Capability
- clientIdClientIdclient_id:client_id
- A client ID, used for identifying this client when publishing messages or for presence purposes. The
clientId
client_id
ClientId
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 aclientId
client_id
ClientId
may also be implicit in a token used to instantiate the library; an error will be raised if aclientId
client_id
ClientId
specified here conflicts with theclientId
client_id
ClientId
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 thenonce
, is used to prevent requests for Ably Token from being replayed.
Type:Integer
Long Integer
Time
NSDate
DateTimeOffset
DateTime
- ttlTtl:ttl
-
1 hour Requested time to live for the Ably Token being created in millisecondsin secondsas a
NSTimeInterval
as aTimeSpan
. When omitted, the Ably REST API default of 60 minutes is applied by Ably
Type:Integer
(milliseconds)Integer
(seconds)NSTimeInterval
Long Integer
TimeSpan
TokenRequest ObjectARTTokenRequestAbly::Models::TokenRequestio.ably.lib.rest.Auth.TokenRequest
TokenRequest
is a type containing parameters for an Ably TokenRequest
. Ably 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 Ably Token in millisecondsin secondsas a
TimeSpan
. If the AblyTokenRequest
is successful, the TTL of the returned Ably Token will be less than or equal to this value depending on application settings and the attributes of the issuing key.
Type:Integer
TimeSpan
NSTimeInterval
- timestampTimestamp
- The timestamp of this request in milliseconds
Type:Integer
Long Integer
Time
DateTimeOffset
NSDate
- capabilityCapability
- Capability of the requested Ably Token. If the Ably
TokenRequest
is successful, the capability of the returned Ably Token will be the intersection of this capability with the capability of the issuing key. The capability is 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 the requested Ably Token. When provided, the Ably 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_jsonTokenRequest.fromMap
TokenRequest.fromJson(String json) → TokenRequestTokenRequest.from_json(String json) → TokenRequestTokenRequest.fromMap(Map<String, dynamic> map)
A static factory methodnamed constructor to create a TokenRequest
from a deserialized TokenRequest
-like object or a JSON stringified TokenRequest
/span>map. 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
fromMap
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 stringifiedTokenRequest
.
Type:Object, String
- map
- a
TokenRequest
-like deserialized map.
Type:Map<String, dynamic>
Returns
A TokenRequest
object
Ably JWT
An Ably JWT is not strictly an Ably construct, rather it is a JWT which has been constructed to be compatible with Ably. The JWT must adhere to the following to ensure compatibility:
-
The JOSE header must include:
-
kid
– Key name, such that an API key ofxVLyHw.vKcU5Q:aZcyqRAf--kjGlwrJ8n_vNShtnVp8jQC8cFWNy4Im1w
will have key namexVLyHw.vKcU5Q
-
-
The JWT claim set must include:
-
iat
– time of issue in seconds -
exp
– expiry time in seconds
-
-
The JWT claim set may include:
-
x-ably-capability
– JSON text encoding of the capability -
x-ably-clientId
– client ID
-
Arbitrary additional claims and headers are supported (apart from those prefixed with x-ably-
which are reserved for future use).
The Ably JWT must be signed with the secret part of your Ably API key using the signature algorithm HS256 (HMAC using the SHA-256 hash algorithm). View the JSON Web Algorithms (JWA) specification for further information.
We recommend you use one of the many JWT libraries available for simplicity when creating your JWTs.
The following is an example of creating an Ably JWT:
var header = {
"typ":"JWT",
"alg":"HS256",
"kid": "xVLyHw.vKcU5Q"
};
var currentTime = Math.round(Date.now()/1000);
var claims = {
"iat": currentTime, /* current time in seconds */
"exp": currentTime + 3600, /* time of expiration in seconds */
"x-ably-capability": "{\"*\":[\"*\"]}"
};
var base64Header = btoa(header);
var base64Claims = btoa(claims);
/* Apply the hash specified in the header */
var signature = hash((base64Header + "." + base64Claims), "aZcyqRAf--kjGlwrJ8n_vNShtnVp8jQC8cFWNy4Im1w");
var ablyJwt = base64Header + "." + base64Claims + "." + signature;
Note: At present Ably does not support asymmetric signatures based on a keypair belonging to a third party. If this is something you’d be interested in, please get in touch.