In any Sync application, your work will span two components.
Since any Twilio SDK-driven app requires an Access Token to run, most will have code like the below to retrieve a token.
1function fetchAccessToken(handler) {2// We use jQuery to make an Ajax request to our server to retrieve our3// Access Token4$.getJSON('/token', function(data) {5// The data sent back from the server should contain a long string, which6// is the token you'll need to initialize the SDK. This string is in a format7// called JWT (JSON Web Token) - more at http://jwt.io8console.log(data.token);910// Since the starter app doesn't implement authentication, the server sends11// back a randomly generated username for the current client, which is how12// they will be identified while sending messages. If your app has a login13// system, you should use the email address or username that uniquely identifies14// a user instead.15console.log(data.identity);1617handler(data);18});19}
In this guide, we'll examine how to handle this request on the server and create a valid token for the client.
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.
1require('dotenv').load();2var http = require('http');3var path = require('path');45var AccessToken = require('twilio').jwt.AccessToken;6var SyncGrant = AccessToken.SyncGrant;7var express = require('express');89// Create Express webapp10var app = express();11app.use(express.static(path.join(__dirname, 'public')));1213/*14Generate an Access Token for a Sync application user - it generates a random15username for the client requesting a token, and takes a device ID as a query16parameter.17*/18app.get('/token', function(request, response) {1920//21// This is the most critical part of your backend code, as you must identify the user and (possibly)22// challenge them with some authentication scheme. To determine the identity, you might use:23// * A session datum consistently identifying one anonymous visitor,24// * A session key identifying a logged-in user25// * OAuth credentials identifying a logged-in user26// * A random username for all comers.27//28var identity = authenticatedSenderOf(request);2930// Create a "grant" identifying the Sync service instance for this app.31var syncGrant = new SyncGrant({32serviceSid: process.env.TWILIO_SYNC_SERVICE_SID,33});3435// Create an access token which we will sign and return to the client,36// containing the grant we just created and specifying his identity.37var token = new AccessToken(38process.env.TWILIO_ACCOUNT_SID,39process.env.TWILIO_API_KEY,40process.env.TWILIO_API_SECRET41);42token.addGrant(syncGrant);43token.identity = identity;4445// Serialize the token to a JWT string and include it in a JSON response46response.send({47identity: identity,48token: token.toJwt()49});50});5152// Create http server and run it53var server = http.createServer(app);54var port = process.env.PORT || 3000;55server.listen(port, function() {56console.log('Express server running on *:' + port);57});58
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.
1fetchAccessToken(initializeSync);23function initializeSync(tokenResponse) {4var syncClient = new Twilio.Sync.Client(tokenResponse.token);56// Use syncClient here7}
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.
1syncClient.on('tokenAboutToExpire', function() {2// Obtain a JWT access token: https://www.twilio.com/docs/sync/identity-and-access-tokens3var token = '<your-access-token-here>';4syncClient.updateToken(token);5});