User Identity & Access Tokens

In your Programmable Chat application, you will be responsible for two components:

  • A client (browser, iOS, Android) app where users send and receive messages
  • A server which vouches for the identity of your users

This guide will show you how these two pieces work together in your messaging application.

Client: Request an Access Token

When a user in their browser or on their mobile device wants to start sending and receiving messages, Twilio can't trust them right away. Not on this Internet! Twilio needs YOU the developer to vouch for your users, so we can trust them too.

You'll need to give your users an Access Token that tells Twilio who they are and what they can do. In our starter apps, the client requests an Access Token from the server like so.

Loading Code Samples...
Language
private void retrieveAccessTokenfromServer() {
    String deviceId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
    String tokenURL = SERVER_TOKEN_URL + "?device=" + deviceId;

    Ion.with(this)
            .load(tokenURL)
            .asJsonObject()
            .setCallback(new FutureCallback<JsonObject>() {
                @Override
                public void onCompleted(Exception e, JsonObject result) {
                    if (e == null) {
                        String identity = result.get("identity").getAsString();
                        String accessToken = result.get("token").getAsString();
                    } else {
                        Toast.makeText(MainActivity.this,
                                R.string.error_retrieving_access_token, Toast.LENGTH_SHORT)
                                .show();
                    }
                }
            });
}
function fetchAccessToken(handler) {
  // We use jQuery to make an Ajax request to the server to retrieve our
  // Access Token
  $.getJSON(
    '/token',
    {
      // we pass along a "device" query parameter to identify the device we
      // are connecting from. You would also pass along any other info needed for
      // your server to establish the identity of the client
      device: 'browser',
    },
    function(data) {
      // The data sent back from the server should contain a long string, which
      // is the token you'll need to initialize the SDK. This string is in a format
      // called JWT (JSON Web Token) - more at http://jwt.io
      console.log(data.token);

      // Since the starter app doesn't implement authentication, the server sends
      // back a randomly generated username for the current client, which is how
      // they will be identified while sending messages. If your app has a login
      // system, you should use the e-mail address or username that uniquely identifies
      // a user instead.
      console.log(data.identity);

      handler(data);
    }
  );
}
// Initialize Chat Client
NSString *identifierForVendor = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
NSString *tokenEndpoint = @"http://localhost:8000/token.php?device=%@";
NSString *urlString = [NSString stringWithFormat:tokenEndpoint, identifierForVendor];

// Make JSON request to server
NSURL *url = [NSURL URLWithString:urlString];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  if (data) {
    NSError *jsonError;
    NSDictionary *tokenResponse = [NSJSONSerialization JSONObjectWithData:data
                                                                  options:kNilOptions
                                                                    error:&jsonError];
    // Handle response from server
    if (!jsonError) {
      self.identity = tokenResponse[@"identity"];
      self.token = tokenResponse[@"token"]  
    } else {
      NSLog(@"error parsing token from server");
    }
  } else {
    NSLog(@"error fetching token from server");
  }
}];
[dataTask resume];
let deviceId = UIDevice.current.identifierForVendor!.uuidString
let urlString = "http://localhost:8000/token.php?device=\(deviceId)"

// Make HTTP request
if let requestURL = URL(string: urlString) {
  let session = URLSession(configuration: URLSessionConfiguration.default)
  let task = session.dataTask(with: requestURL, completionHandler: { (data, response, error) in
      if let data = data {
          do {
              let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String:String]
              let token = json["token"]
              let identity = json["identity"]
          }
          catch let error as NSError {
            print ("Error with json, error = \(error)")
          }
          
      } else {
        print ("Error fetching json, error = \(error)")
      }
  })
  task.resume()
}
Requesting an Access Token

Clients should provide a device ID of some kind to uniquely identify which device they are connecting from. You'll probably want to use vendor ID on iOS and ANDROID_ID on Android. In web applications, there's not a great built-in solution for this, but you might consider using a library like fingerprint.js.

Let's see how we handle this request on the server and create a token for the client.

Server: Create an Access Token

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 figure out who the user is (their identity), 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 as in our starter apps. Who the user is and how you determine that will vary from app to app.

If you determine that the user should indeed be allowed to access your Chat application, you must grant your user access to Chat and configure an Endpoint ID. Here's how we generate those tokens in our starter apps.

Loading Code Samples...
Language
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 6.x
  • 7.x
SDK Version:
  • 2.x
  • 3.x
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 5.x
  • 6.x
SDK Version:
  • 4.x
  • 5.x
require('dotenv').load();
const http = require('http');
const path = require('path');
const AccessToken = require('twilio').AccessToken;
const IpMessagingGrant = AccessToken.IpMessagingGrant;
const express = require('express');
// Create Express webapp
const app = express();
app.use(express.static(path.join(__dirname, 'public')));

/*
Generate an Access Token for a chat application user - it generates a random
username for the client requesting a token, and takes a device ID as a query
parameter.
*/
app.get('/token', (request, response) => {
  const appName = 'TwilioChatDemo';
  const identity = 'John Doe';
  const deviceId = request.query.device;

  // Create a unique ID for the client on their current device
  const endpointId = appName + ':' + identity + ':' + deviceId;

  // Create a "grant" which enables a client to use IPM as a given user,
  // on a given device
  const ipmGrant = new IpMessagingGrant({
    serviceSid: process.env.TWILIO_IPM_SERVICE_SID,
    endpointId: endpointId,
  });

  // Create an access token which we will sign and return to the client,
  // containing the grant we just created
  const token = new AccessToken(
    process.env.TWILIO_ACCOUNT_SID,
    process.env.TWILIO_API_KEY,
    process.env.TWILIO_API_SECRET
  );
  token.addGrant(ipmGrant);
  token.identity = identity;

  // Serialize the token to a JWT string and include it in a JSON response
  response.send({
    identity: identity,
    token: token.toJwt(),
  });
});

// Create http server and run it
const server = http.createServer(app);
const port = process.env.PORT || 3000;
server.listen(port, () => {
  console.log('Express server running on *:' + port);
});
require('dotenv').load();
const http = require('http');
const path = require('path');
const AccessToken = require('twilio').AccessToken;
const ChatGrant = AccessToken.ChatGrant;
const express = require('express');
// Create Express webapp
const app = express();
app.use(express.static(path.join(__dirname, 'public')));

/*
Generate an Access Token for a chat application user - it generates a random
username for the client requesting a token, and takes a device ID as a query
parameter.
*/
app.get('/token', (request, response) => {
  const appName = 'TwilioChatDemo';
  const identity = 'John Doe';
  const deviceId = request.query.device;

  // Create a unique ID for the client on their current device
  const endpointId = appName + ':' + identity + ':' + deviceId;

  // Create a "grant" which enables a client to use Chat as a given user,
  // on a given device
  const chatGrant = new ChatGrant({
    serviceSid: process.env.TWILIO_CHAT_SERVICE_SID,
    endpointId: endpointId,
  });

  // Create an access token which we will sign and return to the client,
  // containing the grant we just created
  const token = new AccessToken(
    process.env.TWILIO_ACCOUNT_SID,
    process.env.TWILIO_API_KEY,
    process.env.TWILIO_API_SECRET
  );
  token.addGrant(chatGrant);
  token.identity = identity;

  // Serialize the token to a JWT string and include it in a JSON response
  response.send({
    identity: identity,
    token: token.toJwt(),
  });
});

// Create http server and run it
const server = http.createServer(app);
const port = process.env.PORT || 3000;
server.listen(port, () => {
  console.log('Express server running on *:' + port);
});
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Twilio;
using Twilio.Auth;
using JWT;
using Faker;

namespace TwilioIpMessaging.Controllers
{
    public class TokenController : Controller
    {
        // GET: /token
        public ActionResult Index(string device)
        {
            // Load Twilio configuration from Web.config
            var accountSid = ConfigurationManager.AppSettings["TwilioAccountSid"];
            var apiKey = ConfigurationManager.AppSettings["TwilioApiKey"];
            var apiSecret = ConfigurationManager.AppSettings["TwilioApiSecret"];
            var ipmServiceSid = ConfigurationManager.AppSettings["TwilioIpmServiceSid"];

            // Create a random identity for the client
            var identity = Internet.UserName();

            // Create an Access Token generator
            var token = new AccessToken(accountSid, apiKey, apiSecret);
            Token.Identity = identity;

            // Create an IP messaging grant for this token
            var grant = new IpMessagingGrant();
            grant.EndpointId = $"TwilioChatDemo:{identity}:{device}";
            grant.ServiceSid = ipmServiceSid;
            token.AddGrant(grant);

            return Json(new {
                identity = identity,
                token = token.ToJWT()
            }, JsonRequestBehavior.AllowGet);
        }
    }
}
<?php
 
require_once('./twilio-php/Services/Twilio.php'); 
require_once('./config.php');

// An identifier for your app - can be anything you'd like
$appName = 'TwilioChatDemo';
// choose a random username for the connecting user
$identity = "John Doe";
// A device ID should be passed as a query string parameter to this script
$deviceId = empty($_GET['device']) ? "unknown" : $_GET['device'];
// The endpoint ID is a combination of the above
$endpointId = $appName . ':' . $identity . ':' . $deviceId;
// Create access token, which we will serialize and send to the client
$token = new Services_Twilio_AccessToken(
    $TWILIO_ACCOUNT_SID, 
    $TWILIO_API_KEY, 
    $TWILIO_API_SECRET, 
    3600, 
    $identity
);

// Create IP Messaging grant
$ipmGrant = new Services_Twilio_Auth_IpMessagingGrant();
$ipmGrant->setServiceSid($TWILIO_IPM_SERVICE_SID);
$ipmGrant->setEndpointId($endpointId);

// Add grant to token
$token->addGrant($ipmGrant);

// return serialized token and the user's randomly generated ID
echo json_encode(array(
    'identity' => $identity,
    'token' => $token->toJWT(),
));
require 'twilio-ruby'
require 'sinatra'
require 'sinatra/json'
require 'dotenv'
require 'faker'

# Load environment configuration
Dotenv.load

# Render home page
get '/' do
  File.read(File.join('public', 'index.html'))
end

# Generate a token for use in our IP Messaging application
get '/token' do
  # Get the user-provided ID for the connecting device
  device_id = params['device']

  # Create a random username for the client
  identity = Faker::Internet.user_name

  # Create a unique ID for the currently connecting device
  endpoint_id = "TwilioDemoApp:#{identity}:#{device_id}"

  # Create an Access Token for IP messaging usage
  token = Twilio::Util::AccessToken.new ENV['TWILIO_ACCOUNT_SID'],
    ENV['TWILIO_API_KEY'], ENV['TWILIO_API_SECRET'], 3600, identity

  # Create IP Messaging grant for our token
  grant = Twilio::Util::AccessToken::IpMessagingGrant.new
  grant.service_sid = ENV['TWILIO_IPM_SERVICE_SID']
  grant.endpoint_id = endpoint_id
  token.add_grant grant

  # Generate the token and send to client
  json :identity => identity, :token => token.to_jwt
end
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using System.Web.Mvc;
using Twilio;
using Twilio.Auth;
using Twilio.Jwt.AccessToken;
using Faker;

namespace TwilioIpMessaging.Controllers
{
    public class TokenController : Controller
    {
        // GET: /token
        public ActionResult Index(string device)
        {
            // Load Twilio configuration from Web.config
            var accountSid = ConfigurationManager.AppSettings["TwilioAccountSid"];
            var apiKey = ConfigurationManager.AppSettings["TwilioApiKey"];
            var apiSecret = ConfigurationManager.AppSettings["TwilioApiSecret"];
            var chatServiceSid = ConfigurationManager.AppSettings["TwilioChatServiceSid"];

            // Create a random identity for the client
            var identity = Internet.UserName();

            // Create an Chat grant for this token
            var grants = new HashSet<IGrant>
            {
                new ChatGrant
                {
                    EndpointId = $"TwilioChatDemo:{identity}:{device}",
                    ServiceSid = chatServiceSid
                }
            };

            // Create an Access Token generator
            var token = new Token(
                accountSid,
                apiKey,
                apiSecret,
                identity,
                grants: grants
            );

            return Json(new {
                identity = identity,
                token = token.ToJwt()
            }, JsonRequestBehavior.AllowGet);
        }
    }
}
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once '/path/to/vendor/autoload.php'; // Loads the library
use Twilio\Jwt\AccessToken;
use Twilio\Jwt\Grants\ChatGrant;

// Required for all Twilio access tokens
$twilioAccountSid = 'ACxxxxxxxxxxxx';
$twilioApiKey = 'SKxxxxxxxxxxxx';
$twilioApiSecret = 'xxxxxxxxxxxxxx';

// Required for Chat grant
$chatServiceSid = 'ISxxxxxxxxxxxx';
// An identifier for your app - can be anything you'd like
$appName = 'TwilioChatDemo';
// choose a random username for the connecting user
$identity = "john_doe";
// A device ID should be passed as a query string parameter to this script
$deviceId = 'somedevice';
$endpointId = $appName . ':' . $identity . ':' . $deviceId;

// Create access token, which we will serialize and send to the client
$token = new AccessToken(
    $twilioAccountSid,
    $twilioApiKey,
    $twilioApiSecret,
    3600,
    $identity
);

// Create Chat grant
$chatGrant = new ChatGrant();
$chatGrant->setServiceSid($chatServiceSid);
$chatGrant->setEndpointId($endpointId);

// Add grant to token
$token->addGrant($chatGrant);

// return serialized token and the user's randomly generated ID
echo json_encode(
    array(
        'identity' => $identity,
        'token' => $token->toJWT(),
    )
);
import os
from flask import Flask, jsonify, request
from faker import Factory
from twilio.access_token import AccessToken, IpMessagingGrant

app = Flask(__name__)
fake = Factory.create()


@app.route('/')
def index():
    return app.send_static_file('index.html')


@app.route('/token')
def token():
    # get credentials for environment variables
    account_sid = os.environ['TWILIO_ACCOUNT_SID']
    api_key = os.environ['TWILIO_API_KEY']
    api_secret = os.environ['TWILIO_API_SECRET']
    service_sid = os.environ['TWILIO_IPM_SERVICE_SID']

    # create a randomly generated username for the client
    identity = fake.user_name()

    # Create a unique endpoint ID for the
    device_id = request.args.get('device')
    endpoint = "TwilioChatDemo:{0}:{1}".format(identity, device_id)

    # Create access token with credentials
    token = AccessToken(account_sid, api_key, api_secret, identity)

    # Create an IP Messaging grant and add to token
    ipm_grant = IpMessagingGrant(endpoint_id=endpoint, service_sid=service_sid)
    token.add_grant(ipm_grant)

    # Return token info as JSON
    return jsonify(identity=identity, token=token.to_jwt())

if __name__ == '__main__':
    app.run(debug=True)
require 'twilio-ruby'
require 'sinatra'
require 'sinatra/json'
require 'dotenv'
require 'faker'

# Load environment configuration
Dotenv.load

# Render home page
get '/' do
  File.read(File.join('public', 'index.html'))
end

# Generate a token for use in our Chat application
get '/token' do
  # Get the user-provided ID for the connecting device
  device_id = params['device']

  # Create a random username for the client
  identity = Faker::Internet.user_name

  # Create a unique ID for the currently connecting device
  endpoint_id = "TwilioDemoApp:#{identity}:#{device_id}"

  # Create an Access Token for Chat usage
  token = Twilio::Util::AccessToken.new(
    ENV['TWILIO_ACCOUNT_SID'],
    ENV['TWILIO_API_KEY'],
    ENV['TWILIO_API_SECRET'],
    3600, identity
  )

  # Create Chat grant for our token
  grant = Twilio::Util::AccessToken::ChatGrant.new
  grant.service_sid = ENV['TWILIO_CHAT_SERVICE_SID']
  grant.endpoint_id = endpoint_id
  token.add_grant grant

  # Generate the token and send to client
  json identity: identity, token: token.to_jwt
end
import com.github.javafaker.Faker;
import com.google.gson.Gson;
import com.twilio.sdk.auth.AccessToken;
import com.twilio.sdk.auth.IpMessagingGrant;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import static spark.Spark.get;
import static spark.Spark.staticFileLocation;

public class WebApp {

  public static void main(String[] args) {
    // Serve static files from src/main/resources/public
    staticFileLocation("/public");

    // Create a Faker instance to generate a random username for the connecting user
    Faker faker = new Faker();

    // Create an access token using our Twilio credentials
    get("/token", "application/json", (request, response) -> {
      // Generate a random username for the connecting client
      String identity = faker.name().firstName() + faker.name().lastName() + faker.address().zipCode();

      // Create an endpoint ID which uniquely identifies the user on their current device
      String appName = "TwilioChatDemo";
      String endpointId = appName + ":" + identity + ":" + request.params("device");

      // Fetch environment info
      Map<String, String> env = new HashMap<String, String>();
      Path path = Paths.get(".env");
      Files.lines(path).forEach(s -> {
        String[] keyVal = s.split("=");
        String key = keyVal[0];
        String val = keyVal[1];
        env.put(key, val);
      });

      // Create IP messaging grant
      IpMessagingGrant grant = new IpMessagingGrant();
      grant.setEndpointId(endpointId);
      grant.setServiceSid(env.get("TWILIO_IPM_SERVICE_SID"));

      // Create access token
      AccessToken token = new AccessToken.Builder(
        System.getenv("TWILIO_ACCOUNT_SID"),
        System.getenv("TWILIO_API_KEY"),
        System.getenv("TWILIO_API_SECRET")
      ).identity(identity).grant(grant).build();

      // create JSON response payload
      HashMap<String, String> json = new HashMap<String, String>();
      json.put("identity", identity);
      json.put("token", token.toJWT());

      // Render JSON response
      Gson gson = new Gson();
      return gson.toJson(json);
    });
  }
}
import os
from flask import Flask, jsonify, request
from faker import Factory
from twilio.jwt.access_token import AccessToken
from twilio.jwt.access_token.grants import ChatGrant

app = Flask(__name__)
fake = Factory.create()


@app.route('/')
def index():
    return app.send_static_file('index.html')


@app.route('/token')
def token():
    # get credentials for environment variables
    account_sid = os.environ['TWILIO_ACCOUNT_SID']
    api_key = os.environ['TWILIO_API_KEY']
    api_secret = os.environ['TWILIO_API_SECRET']
    service_sid = os.environ['TWILIO_CHAT_SERVICE_SID']

    # create a randomly generated username for the client
    identity = fake.user_name()

    # Create a unique endpoint ID for the
    device_id = request.args.get('device')
    endpoint = "TwilioChatDemo:{0}:{1}".format(identity, device_id)

    # Create access token with credentials
    token = AccessToken(account_sid, api_key, api_secret, identity=identity)

    # Create a Chat grant and add to token
    chat_grant = ChatGrant(endpoint_id=endpoint, service_sid=service_sid)
    token.add_grant(chat_grant)

    # Return token info as JSON
    return jsonify(identity=identity, token=token.to_jwt())


if __name__ == '__main__':
    app.run(debug=True)
import static spark.Spark.get;
import static spark.Spark.staticFileLocation;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import com.github.javafaker.Faker;
import com.google.gson.Gson;
import com.twilio.jwt.accesstoken.AccessToken;
import com.twilio.jwt.accesstoken.ChatGrant;

public class WebApp {
  public static void main(String[] args) {
    // Serve static files from src/main/resources/public
    staticFileLocation("/public");

    // Create a Faker instance to generate a random username for the connecting user
    Faker faker = new Faker();

    // Create an access token using our Twilio credentials
    get("/token", "application/json", (request, response) -> {
      // Generate a random username for the connecting client
      String identity =
        faker.name().firstName() + faker.name().lastName() + faker.address().zipCode();

      // Create an endpoint ID which uniquely identifies the user on their current device
      String appName = "TwilioChatDemo";
      String endpointId = appName + ":" + identity + ":" + request.params("device");

      // Fetch environment info
      Map<String, String> env = new HashMap<String, String>();
      Path path = Paths.get(".env");
      Files.lines(path).forEach(s -> {
        String[] keyVal = s.split("=");
        String key = keyVal[0];
        String val = keyVal[1];
        env.put(key, val);
      });

      // Create Chat grant
      ChatGrant grant = new ChatGrant();
      grant.setEndpointId(endpointId);
      grant.setServiceSid(env.get("TWILIO_CHAT_SERVICE_SID"));

      // Create access token
      AccessToken token = new AccessToken.Builder(System.getenv("TWILIO_ACCOUNT_SID"),
          System.getenv("TWILIO_API_KEY"), System.getenv("TWILIO_API_SECRET"))
              .identity(identity)
              .grant(grant)
              .build();

      // create JSON response payload
      HashMap<String, String> json = new HashMap<String, String>();
      json.put("identity", identity);
      json.put("token", token.toJwt());

      // Render JSON response
      Gson gson = new Gson();
      return gson.toJson(json);
    });
  }
}
Creating an Access Token on the Server

About Endpoint IDs

An "endpoint" in Chat is a unique app, device, and user combination that can receive a message. For example, "alice@example.com" using "SquareChat" on her iPhone is a different message delivery destination (endpoint) than "alice@example.com" using "SquareChat" on her Kindle Fire tablet. The endpoint ID you generate on the server - while it can be a string in any format you want - should integrate at least these three dimensions.

Once your client receives an Access Token from your server, you can initialize the Twilio Chat SDK and start sending and receiving messages.

Client: Initialize the SDK with an Access Token

Access Token in hand, we can now initialize the Chat SDK on the client to start doing fun stuff like sending and receiving messages. Here's how you would use the token string to initialize the client, again taken from the starter apps.

Loading Code Samples...
Language
ChatClient.Properties.Builder builder = new ChatClient.Properties.Builder();
builder.setSynchronizationStrategy(ChatClient.SynchronizationStrategy.ALL);
ChatClient.Properties props = builder.createProperties();
ChatClient.create(MainActivity.this,accessToken,props,mChatClientCallback);
var chatClient = new Twilio.Chat.Client('the token string from server');
self.client = [TwilioChatClient chatClientWithToken:tokenResponse[@"token"] 
                                         properties:nil 
                                           delegate:self];
self.client = TwilioChatClient(token: token, properties: nil, delegate: self)
Initializing the client

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

Token Expiry

Before moving on, you'll want to be sure to listen to the tokenExpired event and refresh your token.

Loading Code Samples...
Language
chatClient.on('tokenExpired', refreshToken);   

function refreshToken() {
  fetchAccessToken(setNewToken);
}

function setNewToken(tokenResponse) {
  accessManager.updateToken(tokenResponse.token);
}
Refreshing an Access Token

Now that your token logic is setup, the first thing you're likely to want to do is send and receive messages on a channel. Press on to learn how to make that happen!

Next: Channels and Messages »

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

1 / 1
Loading Code Samples...
private void retrieveAccessTokenfromServer() {
    String deviceId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
    String tokenURL = SERVER_TOKEN_URL + "?device=" + deviceId;

    Ion.with(this)
            .load(tokenURL)
            .asJsonObject()
            .setCallback(new FutureCallback<JsonObject>() {
                @Override
                public void onCompleted(Exception e, JsonObject result) {
                    if (e == null) {
                        String identity = result.get("identity").getAsString();
                        String accessToken = result.get("token").getAsString();
                    } else {
                        Toast.makeText(MainActivity.this,
                                R.string.error_retrieving_access_token, Toast.LENGTH_SHORT)
                                .show();
                    }
                }
            });
}
function fetchAccessToken(handler) {
  // We use jQuery to make an Ajax request to the server to retrieve our
  // Access Token
  $.getJSON(
    '/token',
    {
      // we pass along a "device" query parameter to identify the device we
      // are connecting from. You would also pass along any other info needed for
      // your server to establish the identity of the client
      device: 'browser',
    },
    function(data) {
      // The data sent back from the server should contain a long string, which
      // is the token you'll need to initialize the SDK. This string is in a format
      // called JWT (JSON Web Token) - more at http://jwt.io
      console.log(data.token);

      // Since the starter app doesn't implement authentication, the server sends
      // back a randomly generated username for the current client, which is how
      // they will be identified while sending messages. If your app has a login
      // system, you should use the e-mail address or username that uniquely identifies
      // a user instead.
      console.log(data.identity);

      handler(data);
    }
  );
}
// Initialize Chat Client
NSString *identifierForVendor = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
NSString *tokenEndpoint = @"http://localhost:8000/token.php?device=%@";
NSString *urlString = [NSString stringWithFormat:tokenEndpoint, identifierForVendor];

// Make JSON request to server
NSURL *url = [NSURL URLWithString:urlString];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  if (data) {
    NSError *jsonError;
    NSDictionary *tokenResponse = [NSJSONSerialization JSONObjectWithData:data
                                                                  options:kNilOptions
                                                                    error:&jsonError];
    // Handle response from server
    if (!jsonError) {
      self.identity = tokenResponse[@"identity"];
      self.token = tokenResponse[@"token"]  
    } else {
      NSLog(@"error parsing token from server");
    }
  } else {
    NSLog(@"error fetching token from server");
  }
}];
[dataTask resume];
let deviceId = UIDevice.current.identifierForVendor!.uuidString
let urlString = "http://localhost:8000/token.php?device=\(deviceId)"

// Make HTTP request
if let requestURL = URL(string: urlString) {
  let session = URLSession(configuration: URLSessionConfiguration.default)
  let task = session.dataTask(with: requestURL, completionHandler: { (data, response, error) in
      if let data = data {
          do {
              let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String:String]
              let token = json["token"]
              let identity = json["identity"]
          }
          catch let error as NSError {
            print ("Error with json, error = \(error)")
          }
          
      } else {
        print ("Error fetching json, error = \(error)")
      }
  })
  task.resume()
}
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 6.x
  • 7.x
SDK Version:
  • 2.x
  • 3.x
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 5.x
  • 6.x
SDK Version:
  • 4.x
  • 5.x
require('dotenv').load();
const http = require('http');
const path = require('path');
const AccessToken = require('twilio').AccessToken;
const IpMessagingGrant = AccessToken.IpMessagingGrant;
const express = require('express');
// Create Express webapp
const app = express();
app.use(express.static(path.join(__dirname, 'public')));

/*
Generate an Access Token for a chat application user - it generates a random
username for the client requesting a token, and takes a device ID as a query
parameter.
*/
app.get('/token', (request, response) => {
  const appName = 'TwilioChatDemo';
  const identity = 'John Doe';
  const deviceId = request.query.device;

  // Create a unique ID for the client on their current device
  const endpointId = appName + ':' + identity + ':' + deviceId;

  // Create a "grant" which enables a client to use IPM as a given user,
  // on a given device
  const ipmGrant = new IpMessagingGrant({
    serviceSid: process.env.TWILIO_IPM_SERVICE_SID,
    endpointId: endpointId,
  });

  // Create an access token which we will sign and return to the client,
  // containing the grant we just created
  const token = new AccessToken(
    process.env.TWILIO_ACCOUNT_SID,
    process.env.TWILIO_API_KEY,
    process.env.TWILIO_API_SECRET
  );
  token.addGrant(ipmGrant);
  token.identity = identity;

  // Serialize the token to a JWT string and include it in a JSON response
  response.send({
    identity: identity,
    token: token.toJwt(),
  });
});

// Create http server and run it
const server = http.createServer(app);
const port = process.env.PORT || 3000;
server.listen(port, () => {
  console.log('Express server running on *:' + port);
});
require('dotenv').load();
const http = require('http');
const path = require('path');
const AccessToken = require('twilio').AccessToken;
const ChatGrant = AccessToken.ChatGrant;
const express = require('express');
// Create Express webapp
const app = express();
app.use(express.static(path.join(__dirname, 'public')));

/*
Generate an Access Token for a chat application user - it generates a random
username for the client requesting a token, and takes a device ID as a query
parameter.
*/
app.get('/token', (request, response) => {
  const appName = 'TwilioChatDemo';
  const identity = 'John Doe';
  const deviceId = request.query.device;

  // Create a unique ID for the client on their current device
  const endpointId = appName + ':' + identity + ':' + deviceId;

  // Create a "grant" which enables a client to use Chat as a given user,
  // on a given device
  const chatGrant = new ChatGrant({
    serviceSid: process.env.TWILIO_CHAT_SERVICE_SID,
    endpointId: endpointId,
  });

  // Create an access token which we will sign and return to the client,
  // containing the grant we just created
  const token = new AccessToken(
    process.env.TWILIO_ACCOUNT_SID,
    process.env.TWILIO_API_KEY,
    process.env.TWILIO_API_SECRET
  );
  token.addGrant(chatGrant);
  token.identity = identity;

  // Serialize the token to a JWT string and include it in a JSON response
  response.send({
    identity: identity,
    token: token.toJwt(),
  });
});

// Create http server and run it
const server = http.createServer(app);
const port = process.env.PORT || 3000;
server.listen(port, () => {
  console.log('Express server running on *:' + port);
});
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Twilio;
using Twilio.Auth;
using JWT;
using Faker;

namespace TwilioIpMessaging.Controllers
{
    public class TokenController : Controller
    {
        // GET: /token
        public ActionResult Index(string device)
        {
            // Load Twilio configuration from Web.config
            var accountSid = ConfigurationManager.AppSettings["TwilioAccountSid"];
            var apiKey = ConfigurationManager.AppSettings["TwilioApiKey"];
            var apiSecret = ConfigurationManager.AppSettings["TwilioApiSecret"];
            var ipmServiceSid = ConfigurationManager.AppSettings["TwilioIpmServiceSid"];

            // Create a random identity for the client
            var identity = Internet.UserName();

            // Create an Access Token generator
            var token = new AccessToken(accountSid, apiKey, apiSecret);
            Token.Identity = identity;

            // Create an IP messaging grant for this token
            var grant = new IpMessagingGrant();
            grant.EndpointId = $"TwilioChatDemo:{identity}:{device}";
            grant.ServiceSid = ipmServiceSid;
            token.AddGrant(grant);

            return Json(new {
                identity = identity,
                token = token.ToJWT()
            }, JsonRequestBehavior.AllowGet);
        }
    }
}
<?php
 
require_once('./twilio-php/Services/Twilio.php'); 
require_once('./config.php');

// An identifier for your app - can be anything you'd like
$appName = 'TwilioChatDemo';
// choose a random username for the connecting user
$identity = "John Doe";
// A device ID should be passed as a query string parameter to this script
$deviceId = empty($_GET['device']) ? "unknown" : $_GET['device'];
// The endpoint ID is a combination of the above
$endpointId = $appName . ':' . $identity . ':' . $deviceId;
// Create access token, which we will serialize and send to the client
$token = new Services_Twilio_AccessToken(
    $TWILIO_ACCOUNT_SID, 
    $TWILIO_API_KEY, 
    $TWILIO_API_SECRET, 
    3600, 
    $identity
);

// Create IP Messaging grant
$ipmGrant = new Services_Twilio_Auth_IpMessagingGrant();
$ipmGrant->setServiceSid($TWILIO_IPM_SERVICE_SID);
$ipmGrant->setEndpointId($endpointId);

// Add grant to token
$token->addGrant($ipmGrant);

// return serialized token and the user's randomly generated ID
echo json_encode(array(
    'identity' => $identity,
    'token' => $token->toJWT(),
));
require 'twilio-ruby'
require 'sinatra'
require 'sinatra/json'
require 'dotenv'
require 'faker'

# Load environment configuration
Dotenv.load

# Render home page
get '/' do
  File.read(File.join('public', 'index.html'))
end

# Generate a token for use in our IP Messaging application
get '/token' do
  # Get the user-provided ID for the connecting device
  device_id = params['device']

  # Create a random username for the client
  identity = Faker::Internet.user_name

  # Create a unique ID for the currently connecting device
  endpoint_id = "TwilioDemoApp:#{identity}:#{device_id}"

  # Create an Access Token for IP messaging usage
  token = Twilio::Util::AccessToken.new ENV['TWILIO_ACCOUNT_SID'],
    ENV['TWILIO_API_KEY'], ENV['TWILIO_API_SECRET'], 3600, identity

  # Create IP Messaging grant for our token
  grant = Twilio::Util::AccessToken::IpMessagingGrant.new
  grant.service_sid = ENV['TWILIO_IPM_SERVICE_SID']
  grant.endpoint_id = endpoint_id
  token.add_grant grant

  # Generate the token and send to client
  json :identity => identity, :token => token.to_jwt
end
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using System.Web.Mvc;
using Twilio;
using Twilio.Auth;
using Twilio.Jwt.AccessToken;
using Faker;

namespace TwilioIpMessaging.Controllers
{
    public class TokenController : Controller
    {
        // GET: /token
        public ActionResult Index(string device)
        {
            // Load Twilio configuration from Web.config
            var accountSid = ConfigurationManager.AppSettings["TwilioAccountSid"];
            var apiKey = ConfigurationManager.AppSettings["TwilioApiKey"];
            var apiSecret = ConfigurationManager.AppSettings["TwilioApiSecret"];
            var chatServiceSid = ConfigurationManager.AppSettings["TwilioChatServiceSid"];

            // Create a random identity for the client
            var identity = Internet.UserName();

            // Create an Chat grant for this token
            var grants = new HashSet<IGrant>
            {
                new ChatGrant
                {
                    EndpointId = $"TwilioChatDemo:{identity}:{device}",
                    ServiceSid = chatServiceSid
                }
            };

            // Create an Access Token generator
            var token = new Token(
                accountSid,
                apiKey,
                apiSecret,
                identity,
                grants: grants
            );

            return Json(new {
                identity = identity,
                token = token.ToJwt()
            }, JsonRequestBehavior.AllowGet);
        }
    }
}
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once '/path/to/vendor/autoload.php'; // Loads the library
use Twilio\Jwt\AccessToken;
use Twilio\Jwt\Grants\ChatGrant;

// Required for all Twilio access tokens
$twilioAccountSid = 'ACxxxxxxxxxxxx';
$twilioApiKey = 'SKxxxxxxxxxxxx';
$twilioApiSecret = 'xxxxxxxxxxxxxx';

// Required for Chat grant
$chatServiceSid = 'ISxxxxxxxxxxxx';
// An identifier for your app - can be anything you'd like
$appName = 'TwilioChatDemo';
// choose a random username for the connecting user
$identity = "john_doe";
// A device ID should be passed as a query string parameter to this script
$deviceId = 'somedevice';
$endpointId = $appName . ':' . $identity . ':' . $deviceId;

// Create access token, which we will serialize and send to the client
$token = new AccessToken(
    $twilioAccountSid,
    $twilioApiKey,
    $twilioApiSecret,
    3600,
    $identity
);

// Create Chat grant
$chatGrant = new ChatGrant();
$chatGrant->setServiceSid($chatServiceSid);
$chatGrant->setEndpointId($endpointId);

// Add grant to token
$token->addGrant($chatGrant);

// return serialized token and the user's randomly generated ID
echo json_encode(
    array(
        'identity' => $identity,
        'token' => $token->toJWT(),
    )
);
import os
from flask import Flask, jsonify, request
from faker import Factory
from twilio.access_token import AccessToken, IpMessagingGrant

app = Flask(__name__)
fake = Factory.create()


@app.route('/')
def index():
    return app.send_static_file('index.html')


@app.route('/token')
def token():
    # get credentials for environment variables
    account_sid = os.environ['TWILIO_ACCOUNT_SID']
    api_key = os.environ['TWILIO_API_KEY']
    api_secret = os.environ['TWILIO_API_SECRET']
    service_sid = os.environ['TWILIO_IPM_SERVICE_SID']

    # create a randomly generated username for the client
    identity = fake.user_name()

    # Create a unique endpoint ID for the
    device_id = request.args.get('device')
    endpoint = "TwilioChatDemo:{0}:{1}".format(identity, device_id)

    # Create access token with credentials
    token = AccessToken(account_sid, api_key, api_secret, identity)

    # Create an IP Messaging grant and add to token
    ipm_grant = IpMessagingGrant(endpoint_id=endpoint, service_sid=service_sid)
    token.add_grant(ipm_grant)

    # Return token info as JSON
    return jsonify(identity=identity, token=token.to_jwt())

if __name__ == '__main__':
    app.run(debug=True)
require 'twilio-ruby'
require 'sinatra'
require 'sinatra/json'
require 'dotenv'
require 'faker'

# Load environment configuration
Dotenv.load

# Render home page
get '/' do
  File.read(File.join('public', 'index.html'))
end

# Generate a token for use in our Chat application
get '/token' do
  # Get the user-provided ID for the connecting device
  device_id = params['device']

  # Create a random username for the client
  identity = Faker::Internet.user_name

  # Create a unique ID for the currently connecting device
  endpoint_id = "TwilioDemoApp:#{identity}:#{device_id}"

  # Create an Access Token for Chat usage
  token = Twilio::Util::AccessToken.new(
    ENV['TWILIO_ACCOUNT_SID'],
    ENV['TWILIO_API_KEY'],
    ENV['TWILIO_API_SECRET'],
    3600, identity
  )

  # Create Chat grant for our token
  grant = Twilio::Util::AccessToken::ChatGrant.new
  grant.service_sid = ENV['TWILIO_CHAT_SERVICE_SID']
  grant.endpoint_id = endpoint_id
  token.add_grant grant

  # Generate the token and send to client
  json identity: identity, token: token.to_jwt
end
import com.github.javafaker.Faker;
import com.google.gson.Gson;
import com.twilio.sdk.auth.AccessToken;
import com.twilio.sdk.auth.IpMessagingGrant;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import static spark.Spark.get;
import static spark.Spark.staticFileLocation;

public class WebApp {

  public static void main(String[] args) {
    // Serve static files from src/main/resources/public
    staticFileLocation("/public");

    // Create a Faker instance to generate a random username for the connecting user
    Faker faker = new Faker();

    // Create an access token using our Twilio credentials
    get("/token", "application/json", (request, response) -> {
      // Generate a random username for the connecting client
      String identity = faker.name().firstName() + faker.name().lastName() + faker.address().zipCode();

      // Create an endpoint ID which uniquely identifies the user on their current device
      String appName = "TwilioChatDemo";
      String endpointId = appName + ":" + identity + ":" + request.params("device");

      // Fetch environment info
      Map<String, String> env = new HashMap<String, String>();
      Path path = Paths.get(".env");
      Files.lines(path).forEach(s -> {
        String[] keyVal = s.split("=");
        String key = keyVal[0];
        String val = keyVal[1];
        env.put(key, val);
      });

      // Create IP messaging grant
      IpMessagingGrant grant = new IpMessagingGrant();
      grant.setEndpointId(endpointId);
      grant.setServiceSid(env.get("TWILIO_IPM_SERVICE_SID"));

      // Create access token
      AccessToken token = new AccessToken.Builder(
        System.getenv("TWILIO_ACCOUNT_SID"),
        System.getenv("TWILIO_API_KEY"),
        System.getenv("TWILIO_API_SECRET")
      ).identity(identity).grant(grant).build();

      // create JSON response payload
      HashMap<String, String> json = new HashMap<String, String>();
      json.put("identity", identity);
      json.put("token", token.toJWT());

      // Render JSON response
      Gson gson = new Gson();
      return gson.toJson(json);
    });
  }
}
import os
from flask import Flask, jsonify, request
from faker import Factory
from twilio.jwt.access_token import AccessToken
from twilio.jwt.access_token.grants import ChatGrant

app = Flask(__name__)
fake = Factory.create()


@app.route('/')
def index():
    return app.send_static_file('index.html')


@app.route('/token')
def token():
    # get credentials for environment variables
    account_sid = os.environ['TWILIO_ACCOUNT_SID']
    api_key = os.environ['TWILIO_API_KEY']
    api_secret = os.environ['TWILIO_API_SECRET']
    service_sid = os.environ['TWILIO_CHAT_SERVICE_SID']

    # create a randomly generated username for the client
    identity = fake.user_name()

    # Create a unique endpoint ID for the
    device_id = request.args.get('device')
    endpoint = "TwilioChatDemo:{0}:{1}".format(identity, device_id)

    # Create access token with credentials
    token = AccessToken(account_sid, api_key, api_secret, identity=identity)

    # Create a Chat grant and add to token
    chat_grant = ChatGrant(endpoint_id=endpoint, service_sid=service_sid)
    token.add_grant(chat_grant)

    # Return token info as JSON
    return jsonify(identity=identity, token=token.to_jwt())


if __name__ == '__main__':
    app.run(debug=True)
import static spark.Spark.get;
import static spark.Spark.staticFileLocation;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import com.github.javafaker.Faker;
import com.google.gson.Gson;
import com.twilio.jwt.accesstoken.AccessToken;
import com.twilio.jwt.accesstoken.ChatGrant;

public class WebApp {
  public static void main(String[] args) {
    // Serve static files from src/main/resources/public
    staticFileLocation("/public");

    // Create a Faker instance to generate a random username for the connecting user
    Faker faker = new Faker();

    // Create an access token using our Twilio credentials
    get("/token", "application/json", (request, response) -> {
      // Generate a random username for the connecting client
      String identity =
        faker.name().firstName() + faker.name().lastName() + faker.address().zipCode();

      // Create an endpoint ID which uniquely identifies the user on their current device
      String appName = "TwilioChatDemo";
      String endpointId = appName + ":" + identity + ":" + request.params("device");

      // Fetch environment info
      Map<String, String> env = new HashMap<String, String>();
      Path path = Paths.get(".env");
      Files.lines(path).forEach(s -> {
        String[] keyVal = s.split("=");
        String key = keyVal[0];
        String val = keyVal[1];
        env.put(key, val);
      });

      // Create Chat grant
      ChatGrant grant = new ChatGrant();
      grant.setEndpointId(endpointId);
      grant.setServiceSid(env.get("TWILIO_CHAT_SERVICE_SID"));

      // Create access token
      AccessToken token = new AccessToken.Builder(System.getenv("TWILIO_ACCOUNT_SID"),
          System.getenv("TWILIO_API_KEY"), System.getenv("TWILIO_API_SECRET"))
              .identity(identity)
              .grant(grant)
              .build();

      // create JSON response payload
      HashMap<String, String> json = new HashMap<String, String>();
      json.put("identity", identity);
      json.put("token", token.toJwt());

      // Render JSON response
      Gson gson = new Gson();
      return gson.toJson(json);
    });
  }
}
ChatClient.Properties.Builder builder = new ChatClient.Properties.Builder();
builder.setSynchronizationStrategy(ChatClient.SynchronizationStrategy.ALL);
ChatClient.Properties props = builder.createProperties();
ChatClient.create(MainActivity.this,accessToken,props,mChatClientCallback);
var chatClient = new Twilio.Chat.Client('the token string from server');
self.client = [TwilioChatClient chatClientWithToken:tokenResponse[@"token"] 
                                         properties:nil 
                                           delegate:self];
self.client = TwilioChatClient(token: token, properties: nil, delegate: self)
chatClient.on('tokenExpired', refreshToken);   

function refreshToken() {
  fetchAccessToken(setNewToken);
}

function setNewToken(tokenResponse) {
  accessManager.updateToken(tokenResponse.token);
}