Skip to contentSkip to navigationSkip to topbar
Rate this Page:

Issuing Sync Tokens


In any Sync application, your work will span two components.

  • An SDK-driven client app (browser, iOS, Android), where users interact with Sync objects.
  • A backend server which vouches for your users' identities by providing Access Tokens .

Since any Twilio SDK-driven app requires an Access Token to run, most will have code like the below to retrieve a token.


_19
function fetchAccessToken(handler) {
_19
// We use jQuery to make an Ajax request to our server to retrieve our
_19
// Access Token
_19
$.getJSON('/token', function(data) {
_19
// The data sent back from the server should contain a long string, which
_19
// is the token you'll need to initialize the SDK. This string is in a format
_19
// called JWT (JSON Web Token) - more at http://jwt.io
_19
console.log(data.token);
_19
_19
// Since the starter app doesn't implement authentication, the server sends
_19
// back a randomly generated username for the current client, which is how
_19
// they will be identified while sending messages. If your app has a login
_19
// system, you should use the email address or username that uniquely identifies
_19
// a user instead.
_19
console.log(data.identity);
_19
_19
handler(data);
_19
});
_19
}

In this guide, we'll examine how to handle this request on the server and create a valid token for the client.


Minting an Access Token in your Backend

minting-an-access-token-in-your-backend page anchor

On the server we must decide, based on the token request that was sent to us, who the user is and what they should be allowed to do. To do this you might use your existing login system (using session cookies, an API token, or whatever mechanism you use to secure API requests or pages today). You might not care who a user is at all, and assign them a temporary identity. Who the user is and how you determine that will vary from app to app.

Assuming that the requesting user is authorized, your backend should respond with a signed token. Here's an example of generating those tokens in Node.js.

We recommend following the standard URI specification and avoid the following reserved characters ! * ' ( ) ; : @ & = + $ , / ? % # [ ] for values such as identity and friendly name.


_57
require('dotenv').load();
_57
var http = require('http');
_57
var path = require('path');
_57
_57
var AccessToken = require('twilio').jwt.AccessToken;
_57
var SyncGrant = AccessToken.SyncGrant;
_57
var express = require('express');
_57
_57
// Create Express webapp
_57
var app = express();
_57
app.use(express.static(path.join(__dirname, 'public')));
_57
_57
/*
_57
Generate an Access Token for a Sync application user - it generates a random
_57
username for the client requesting a token, and takes a device ID as a query
_57
parameter.
_57
*/
_57
app.get('/token', function(request, response) {
_57
_57
//
_57
// This is the most critical part of your backend code, as you must identify the user and (possibly)
_57
// challenge them with some authentication scheme. To determine the identity, you might use:
_57
// * A session datum consistently identifying one anonymous visitor,
_57
// * A session key identifying a logged-in user
_57
// * OAuth credentials identifying a logged-in user
_57
// * A random username for all comers.
_57
//
_57
var identity = authenticatedSenderOf(request);
_57
_57
// Create a "grant" identifying the Sync service instance for this app.
_57
var syncGrant = new SyncGrant({
_57
serviceSid: process.env.TWILIO_SYNC_SERVICE_SID,
_57
});
_57
_57
// Create an access token which we will sign and return to the client,
_57
// containing the grant we just created and specifying his identity.
_57
var token = new AccessToken(
_57
process.env.TWILIO_ACCOUNT_SID,
_57
process.env.TWILIO_API_KEY,
_57
process.env.TWILIO_API_SECRET
_57
);
_57
token.addGrant(syncGrant);
_57
token.identity = identity;
_57
_57
// Serialize the token to a JWT string and include it in a JSON response
_57
response.send({
_57
identity: identity,
_57
token: token.toJwt()
_57
});
_57
});
_57
_57
// Create http server and run it
_57
var server = http.createServer(app);
_57
var port = process.env.PORT || 3000;
_57
server.listen(port, function() {
_57
console.log('Express server running on *:' + port);
_57
});


Applying the minted token to your SDK

applying-the-minted-token-to-your-sdk page anchor

Access Token in hand, we can now initialize the Sync SDK on the client to start doing fun stuff like subscribing to Sync objects. Here's how you would use the token string to initialize the client in JavaScript.


_10
fetchAccessToken(initializeSync);
_10
_10
function initializeSync(tokenResponse) {
_10
var syncClient = new Twilio.Sync.Client(tokenResponse.token);
_10
_10
// Use syncClient here
_10
}

After you've initialized the client, you can access all of the SDK's features.


After supplying the access token to Sync SDK initially, renewing the token prior to its expiry is important for ensuring that your Sync application is a great user experience. For long living applications, you should refresh the token when either tokenAboutToExpire or tokenExpired events occur. Handling just one of them is sufficient. The tokenAboutToExpire trigger takes place three minutes before the JWT access token expiry.


_10
syncClient.on('tokenAboutToExpire', function() {
_10
// Obtain a JWT access token: https://www.twilio.com/docs/sync/identity-and-access-tokens
_10
var token = '<your-access-token-here>';
_10
syncClient.updateToken(token);
_10
});


Rate this Page: