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
.
The Auth object is available as the auth
property of an Ably Realtime client instance.
Auth Properties
The Auth
object exposes the following public properties:
clientId
The client ID string, if any, configured for this client connection. See identified clients for more information on trusted client identifiers.
Auth Methods
authorize
authorize(TokenParams tokenParams, AuthOptions authOptions, callback(ErrorInfo err, TokenDetails tokenDetails))
Instructs the library to get a new token immediately. Once fetched, it will upgrade the current realtime connection to use the new token, or if not connected, will initiate a connection to Ably once the new token has been obtained. Also stores any tokenParams
and authOptions
passed in as the new defaults, to be used for all subsequent implicit or explicit token requests.
Any tokenParams
and authOptions
objects passed in will entirely replace (as opposed to being merged with) the currently client library saved tokenParams
and authOptions
.
Parameters
- tokenParams
- an optional object containing the token parameters for the authorization requestType:
TokenParams
- authOptions
- an optional object containing the authentication options for the authorization requestType:
AuthOptions
Example
client.auth.authorize({ clientId: 'bob' }, function(err, tokenDetails) {
if(err) {
console.log('An error occurred; err = ' + err.toString());
} else {
console.log('Success! Realtime connection upgraded with new token: ' +
tokenDetails.token);
}
});
CopyCopied!
createTokenRequest
createTokenRequest(TokenParams tokenParams, AuthOptions authOptions, callback(ErrorInfo err, TokenRequest tokenRequest))
Creates and signs an Ably TokenRequest
based on the specified (or if none specified, the client library stored) tokenParams
and authOptions
. Note this can only be used when the API key
value is available locally. Otherwise, the Ably TokenRequest
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 authOptions
and tokenParams
are optional. When 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 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 a token, see Token Authentication explained.
Parameters
- tokenParams
- an optional object containing the token parameters for the Ably Token requestType:
TokenParams
- authOptions
- an optional object containing the authentication optionsType:
AuthOptions
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);
}
});
CopyCopied!
requestToken
requestToken(TokenParams tokenParams, AuthOptions authOptions, callback(ErrorInfo err, TokenDetails tokenDetails))
Calls the requestToken
REST API endpoint to obtain an Ably Token according to the specified tokenParams
and authOptions
.
Both authOptions
and tokenParams
are optional. When 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 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 a token, see Token Authentication explained.
Parameters
- tokenParams
- an optional object containing the token parameters for the requested tokenType:
TokenParams
- authOptions
- an optional object containing the authentication options for the requested Ably TokenType:
AuthOptions
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);
}
});
CopyCopied!
Related types
AuthOptions Object
Properties
- authCallback
- A function 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 signed
TokenRequest
; aTokenDetails
(in JSON format); an Ably JWT. See our authentication documentation for details of the Ably TokenRequest format and associated API calls.Type:Callable
- authUrl
- 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
- authMethod
GET
The HTTP verb to use for the request, eitherGET
orPOST
Type:String
- authHeaders
- A set of key value pair headers to be added to any request made to the
authUrl
. Useful when an application requires these to be added to validate the request or implement the response. Type:Object
- authParams
- A set of key value pair params to be added to any request made to the
authUrl
. When theauthMethod
isGET
, query params are added to the URL, whereas whenauthMethod
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
- tokenDetails
- 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
orauthCallback
. Use this option if you wish to use Token authentication. Read more about Token authenticationType:TokenDetails
- key
- 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 usedType:String
- queryTime
- 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
- token
- An authenticated token. This can either be a
TokenDetails
object, aTokenRequest
object, or token string (obtained from thetoken
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
or authCallback. Read more about Token authenticationType:String
,TokenDetails
orTokenRequest
TokenDetails Object
TokenDetails
is a type providing details of Ably Token string and its associated metadata.
Properties
- token
- The Ably Token itself. A typical Ably Token string may appear like
{{TOKEN}}
Type:String
- expires
- The time (in milliseconds since the epoch) at which this token expiresType:
Integer
- issued
- The time (in milliseconds since the epoch) at which this token was issuedType:
Integer
- capability
- 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 capabilitiesType:
String
- clientId
- 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 clientType:
String
TokenDetails constructors
TokenDetails.fromJson
TokenDetails.fromJson(String 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 stringifiedTokenDetails
.Type:Object, String
Returns
A TokenDetails
object
TokenParams Object
Properties
- 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
- clientId
- A client ID, used for identifying this client when publishing messages or for presence purposes. The
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
may also be implicit in a token used to instantiate the library; an error will be raised if aclientId
specified here conflicts with theclientId
implicit in the token. Find out more about client identitiesType:String
- 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
- timestamp
- The timestamp (in milliseconds since the epoch) of this request.
timestamp
, in conjunction with thenonce
, is used to prevent requests for Ably Token from being replayed.Type:Integer
- ttl
- 1 hour Requested time to live for the Ably Token being created in milliseconds When omitted, the Ably REST API default of 60 minutes is applied by AblyType:
Integer
(milliseconds)
TokenRequest Object
TokenRequest
is a type containing parameters for an Ably TokenRequest
. Ably Tokens are requested using Auth#requestToken
Properties
- keyName
- The key name of the key against which this request is made. The key name is public, whereas the key secret is privateType:
String
- ttl
- Requested time to live for the Ably Token in milliseconds. If the Ably
TokenRequest
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
- timestamp
- The timestamp of this request in millisecondsType:
Integer
- capability
- 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 capabilitiesType:String
- clientId
- 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 IDType:
String
- nonce
- An opaque nonce string of at least 16 charactersType:
String
- mac
- The Message Authentication Code for this requestType:
String
TokenRequest constructors
TokenRequest.fromJson
TokenRequest.fromJson(String json) → TokenRequest
A static factory method to create a TokenRequest
from a deserialized TokenRequest
-like object or a JSON stringified TokenRequest
/span><span lang=“flutter”>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
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
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 of{{API_KEY}}
will have key name{{API_KEY_NAME}}
- The JWT claim set must include:
iat
– time of issue in secondsexp
– expiry time in seconds
- The JWT claim set may include:
x-ably-capability
– JSON text encoding of the capabilityx-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": "{{API_KEY_NAME}}"
};
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), "{{API_KEY_SECRET}}");
var ablyJwt = base64Header + "." + base64Claims + "." + signature;
CopyCopied!
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.