clientId.
Token authentication is the recommended authentication method to use client-side for the following reasons:
- Tokens ensure that an Ably API key isn’t exposed in client applications.
- Tokens are short-lived so there is only a short period of time during which a compromised token can be used.
- Tokens provide more fine-grained access control, which also limits the area of exposure a compromised token can access.
- Tokens support functionality not available with Basic auth, such as user claims.
How token authentication works
- Your client calls
authUrlorauthCallbackto request a token from your server. - Your server validates the client and returns a token (JWT, TokenRequest, or Ably Token).
- The client uses this token to authenticate with Ably.
- Tokens are short-lived and expire after a set period.
- The client SDK automatically requests a new token before expiry, ensuring uninterrupted connectivity.
Using authCallback
TheauthCallback is a function that the SDK calls when it needs a token. Your callback should request a token from your server and return it:
Using authUrl
TheauthUrl is a URL that the SDK calls to obtain a token. The SDK will make an HTTP request to this URL and expect a token in the response:
Token types
Ably supports two token formats:JWT (recommended)
JWTs are the recommended approach for most applications:- No Ably SDK required on your server. Any JWT library works.
- Supports channel-scoped claims for trusted metadata
- Supports per-connection rate limits
- Stateless and ideal for serverless environments
Ably Tokens
Ably tokens are an alternative mechanism:- TokenRequest: Server creates a signed request locally, client exchanges it with Ably
- Ably Token (direct): Server requests token from Ably, passes it to client
- Your capability list is very large (JWTs must fit within HTTP header limits)
- You need to keep capabilities confidential (clients can decode JWTs)
Token refresh
One of the important benefits of using an Ably SDK is that automatic token refresh is handled for you. When you provide either anauthUrl or an authCallback, the SDK automatically:
- Calls your auth endpoint when connecting
- Requests a new token before the current token expires
- Maintains the connection seamlessly during refresh
Token TTL limits
Ably enforces maximum TTL (time-to-live) limits:- Access tokens: Maximum TTL of 24 hours.
- Device tokens (for push notifications): Maximum TTL of 5 years.
- Revocable tokens: Maximum TTL of 1 hour. A token is revocable if token revocation has been enabled for the API key used to issue it.
Server-side token generation
Your server should generate tokens using the Ably SDK. Here’s an example:Next steps
- Learn about JWT authentication
- Learn about Ably Tokens
- Understand capabilities for access control
- Explore identified clients
- Learn about token revocation
