Token authentication uses a trusted device with an API key to issue time-limited tokens to untrusted clients. Tokens have a limited set of access rights, known as capabilities, and can have a specific identity using a clientId.
Token authentication is the recommended authentication method to use client-side as it provides more fine-grained access control and limits the risk of credentials being exposed.
Access restrictions
Token-based client validation
Token authentication enables you to validate client characteristics (such as origin, IP address, cookies, or any other client features) in your authentication server before issuing tokens. This provides flexible access control as you can implement any validation logic in your auth server as part of the token issuance process.
API key restrictions
For cases where token authentication is impractical, Ably can add origin or IP address restrictions directly to API keys. However, this approach has significant limitations:
- Less flexible than token authentication.
- Manual intervention required to modify restrictions.
- Enterprise support packages only: contact Ably support if interested.
- Not a security boundary: origin headers can be easily spoofed, especially outside browser contexts.
- Permissive fallback: requests with no origin header are allowed when origin restrictions are set.
For maximum security and flexibility, token authentication with server-side validation is the recommended approach.
Any of the following cause an SDK to use token authentication:
- An
authUrlorauthCallbackis provided that returns an Ably-compatible token or an AblyTokenRequest. useTokenAuthis true.- A
tokenortokenDetailsproperty is provided.
Providing a literal token or tokenDetails is typically used for testing: since tokens are short-lived, in production you typically want to use an authentication method that allows the client library to renew the token automatically before the current token expires.
Authentication using tokens can be achieved requesting and issuing Ably Tokens or passing a JSON Web Tokens (JWT) to the Ably service.
Token refresh
One of the important benefits of using an Ably SDK is that the automatic refresh of tokens will be handled for you.
To use automatic refresh of tokens, provide either an authUrl or an authCallback. When the token is near to expiry the authUrl or authCallback is invoked and a new token is automatically requested.
Token authentication workflow
Understanding how token authentication works helps clarify why automatic renewal is essential:
- Your server uses the Ably API key to request a 'Token Request' object from Ably.
- Your client uses this 'Token Request' object to request the actual token from the Ably server every time it needs to authenticate.
- These tokens are short-lived and expire after a certain period of time.
- The client SDK automatically requests a new token just before the previous one expires, ensuring the connection never drops due to authentication failure.
Using an authUrl or authCallback ensures your client automatically requests a new token when needed, making the authentication process seamless and preventing service interruptions.
An authURL is recommended for use with web-based clients as they can easily utilize cookies and other web-only features. For non-web clients, authCallback is the recommended strategy.
Token TTL limits
Ably enforces maximum TTL (time-to-live) limits on different types of tokens:
- Access tokens: Maximum TTL of 24 hours.
- Device tokens (for push notifications): Maximum TTL of 5 years.
- Revocable tokens: Maximum TTL of 1 hour (when token revocation is enabled).
authUrl
You can specify an authUrl when you create the Ably client. For example:
1
const realtime = new Ably.Realtime({ authUrl: '/auth' });The client will obtain a token, JWT, or tokenRequest from the URL and use it to authenticate requests to Ably. Before token expiry, a request for a new token will be made automatically by the client to the authUrl.
authCallback
You can specify an authentication callback function when you create the Ably client. Inside authCallback, you can make a network request to your servers to generate the tokenRequest. For example:
1
2
3
4
5
6
7
8
9
10
11
12
const ablyClient = new Realtime({
authCallback: async (tokenParams, callback) => {
let tokenRequest;
try {
tokenRequest = await obtainTokenRequest(); // Make a network request to your server
} catch (err) {
callback(err, null);
return;
}
callback(null, tokenRequest);
}
});The tokenParams argument in authCallback is available for convenience, allowing you to see the capabilities, clientId, and other details requested by the client. However, tokenParams should not be trusted or used to generate the tokenRequest on the server side. Instead it is recommended that your createTokenRequest API authenticates clients separately, for example based on cookies, headers, or HTTP body.
AuthOptions
Use properties set with AuthOptions to override the default authentication values set when instantiating a client. You can also embed AuthOptions into your ClientOptions while instantiating.
There are several AuthOptions you can specify along with authUrl and authCallback:
authMethod:- whenauthUrlis called, the defaultGETmethod will be used, unlessPOSTis specified.authHeaders:- allows you to pass additional headers as required, depending on your use case.authParams:- allows you to pass additional query parameters, depending on your use case.
The following is an example of passing AuthOptions:
1
2
3
4
5
6
const realtime = new Ably.Realtime({
authUrl: "/auth",
authMethod: "POST",
authParams: {p1: param1, b: param2},
authHeaders: {h1: header1, h2: header2}
});Ably Tokens
Ably Tokens can be used to authenticate with Ably in the following ways:
- Ably TokenRequest is created by your servers and passed to clients.
- An Ably Token is issued by your servers and passed to clients.
Note that the machine on which you are running your auth server should have an accurate clock, as tokens and TokenRequest contain a timestamp. You can use an NTP daemon, or if you are not able to control your server's clock, you can wish to use the queryTime auth option.
Ably TokenRequest
Using an Ably SDK, a TokenRequest is generated from your server and returned to the client-side SDK instance. The client-side SDK instance then uses the TokenRequest to request an Ably Token from Ably, and subsequently authenticates using that Ably Token.
This is the recommended approach for client-side authentication, for the following reasons:
- An Ably
TokenRequestcan be generated securely by your servers without communicating with Ably. - Your secret API key is never shared with Ably or your clients.
- An Ably
TokenRequestcannot be tampered with due to being signed, must be used soon after creation, and can only be used once.
The process used by Ably SDKs to authenticate with Ably using a TokenRequest is illustrated in the following diagram: