4

I am implementing Video calling api for my project, when i create Access Token from https://www.twilio.com/user/account/video/dev-tools/testing-tools by "Generate Access Token" option it will give me new generated token and when i use it as below

var accessToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImN0eSI6InR3aWxpby1mcGE7dj0xIn0.eyJqdGkiOiJTSzk3ZDI2NGIyOTU1YjM2OWMyOGU4MjA4M2E5MjlmMmE0LTE0NjYwODE1NzQiLCJpc3MiOiJTSzk3ZDI2NGIyOTU1YjM2OWMyOGU4MjA4M2E5MjlmMmE0Iiwic3ViIjoiQUM5ZWE5YjY3ZmM3ZjBjMzE2NTBjNGRmNzkyYzhjYjI2NiIsImV4cCI6MTQ2NjA4NTE3NCwiZ3JhbnRzIjp7ImlkZW50aXR5IjoiQUM5ZWE5YjY3ZmM3ZjBjMzE2NTBjNGRmNzkyYzhjYjI2NiIsInJ0YyI6eyJjb25maWd1cmF0aW9uX3Byb2ZpbGVfc2lkIjoiVlMwNmYzZDdiNTczNGVlYTJhZDdjMWEzYzY4YmMzNjhjNSJ9fX0.976iQ2bMB_tAORxjGkgZFJ-UYGfTidTwfvV0fzySMP0";

var accessManager = new Twilio.AccessManager(accessToken); 

it will works great for me.

Now when i use 2nd option "Generate an Access Token via Helper Library with PHP" and try to generate token with

// Create an Access Token
$token = new Services_Twilio_AccessToken(
    $accountSid,
    $apiKeySid,
    $apiKeySecret,
    $ttl=3600,
    $identity=$identity
);

// Grant access to Conversations
$grant = new Services_Twilio_Auth_ConversationsGrant();
$grant->setConfigurationProfileSid($configurationProfileSid);
$token->addGrant($grant);

echo json_encode(array(
    'identity' => $identity,
    'token' => $token->toJWT(),
));

it will also generate token for me but when i use generated token as

Response Token:

{"identity":"GoldenZeldaGunsight","token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImN0eSI6InR3aWxpby1mcGE7dj0xIn0
.eyJqdGkiOiJTSzk3ZDI2NGIyOTU1YjM2OWMyOGU4MjA4M2E5MjlmMmE0LTE0NjYxMzc4MTkiLCJpc3MiOiJTSzk3ZDI2NGIyOTU
1YjM2OWMyOGU4MjA4M2E5MjlmMmE0Iiwic3ViIjoiQUM5ZWE5YjY3ZmM3ZjBjMzE2NTBjNGRmNzkyYzhjYjI2NiIsIm5iZiI6MTQ
2NjEzNzgxOSwiZXhwIjoxNDY2MTQxNDE5LCJncmFudHMiOnsiaWRlbnRpdHkiOiJHb2xkZW5aZWxkYUd1bnNpZ2h0IiwicnRjIjp7ImNvbmZpZ3VyYXRpb25fcHJvZmlsZV9zaWQiOiJWUzA2ZjNkN2I1NzM0ZWVhMmFkN2MxYTNjNjhiYzM2OGM1In19fQ
.vkOxI1tMIWNQVm1AUL1ySTZY5ZyjYDTdvWCKnVIkLmk"}

I use this response token in

var accessManager = new Twilio.AccessManager(data.token);

it will not works for me. it will give me error like

"Could not connect to Twilio: undefined..."

Response :

Thu Jun 23 2016 13:22:58 GMT+0530 (India Standard Time) | sip.transport | received WebSocket text message:

SIP/2.0 403 Forbidden
CSeq: 81 REGISTER
Call-ID: 4704t9hejng0hmhih2ui8m
From: <sip:AC9ea9b67fc7f0c31650c4df792c8cb266@AC9ea9b67fc7f0c31650c4df792c8cb266.endpoint.twilio.com>;tag=l3bsmhddlr
To: <sip:AC9ea9b67fc7f0c31650c4df792c8cb266@AC9ea9b67fc7f0c31650c4df792c8cb266.endpoint.twilio.com>;tag=72132201_50f4772f_8dc5c7c0-ce8e-4a6e-803a-72f6c761338b
Via: SIP/2.0/WSS 127.0.0.1:60911;branch=z9hG4bK2792018;rport=60911
Server: Twilio
X-Twilio-Error: 31201 Authentication failed
Content-Length: 0

Also i have tested both token on https://jwt.io , its working perfect for me.

Can anyone please help me in this matter where i am wrong with code , if you want then i can pass other credentials details as well ?

Thanks in advance.

Solved

Guys, I'v got solution of this issue with the help of Support.

Solution

In my old version of /Services/Twilio/AccessToken.php , I have an attribute "nbf": 1466743969(not-before time), which means it is not valid until04:52:49 UTC. However according to the timestamp in the log file it was04:50:27 UTC (10:20:27 IST)`. If the system clock of the server generating the access token is a couple minutes fast it will result in an invalid not-before time.

Later versions of the twilio-php library omitted the "nbf" attribute by default, because of this clock skew issue. If you get the latest version of AccessToken.php here:

https://github.com/twilio/twilio-php/blob/master/Services/Twilio/AccessToken.php

it will generate access tokens without "nbf".

An alternate fix would be to make sure the server time is accurate, but you would need administrator access to adjust it.

Brijal Savaliya
  • 1,101
  • 9
  • 19

2 Answers2

3

You don't seem to have included twilio's capability.php. According to the twilio docs, your php should look similar to this

include '/pathto/Services/Twilio/Capability.php';

// Twilio API credentials here
$accountSid = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$authToken  = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy';

$capability = new Services_Twilio_Capability($accountSid, $authToken);
$capability->allowClientOutgoing('APabe7650f654fc34655fc81ae71caa3ff');
$token = $capability->generateToken();

then you access the token via js:

     <script type="text/javascript">

      Twilio.Device.setup("<?php echo $token; ?>");

      Twilio.Device.ready(function (device) {
        $("#log").text("Ready");
      });

      Twilio.Device.error(function (error) {
        $("#log").text("Error: " + error.message);
      });

      Twilio.Device.connect(function (conn) {
        $("#log").text("Successfully established call");
      });

      function call() {
        Twilio.Device.connect();
      }
    </script>

I hope this sets you on the right track.

EDIT:

I didn't realise the above script was for Audio, so just for future users, thought i'd post the video scripts here

  1. Client: Request an Access Token (use jquery)

    $.getJSON('/token', function(data) {
    // The data sent back from the server should contain a long string - this is
    // the JWT token you need to initialize the SDK. Read more about JWT 
    // (JSON Web Token) at http://jwt.io
    console.log(data.token);
    
    //If your app has an existing authentication system, you can use
    // the e-mail address or username that uniquely identifies a user instead.
     console.log(data.identity);
    });
    
  2. Server: Create an Access Token (php)

      <?php
      require_once('./twilio-php/Services/Twilio.php');
      require_once('./randos.php');
      require_once('./config.php');
    
      // choose a random username for the connecting user
       $identity = randomUsername();
    
      // 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
       );
    
      // Grant access to Conversations
      $grant = new Services_Twilio_Auth_ConversationsGrant();
      $grant->setConfigurationProfileSid($TWILIO_CONFIGURATION_SID);
      $token->addGrant($grant);
    
      // return serialized token and the user's randomly generated ID
      echo json_encode(array(
        'identity' => $identity,
        'token' => $token->toJWT(),
     ));
    
  3. Client: Initialize the SDK with an Access Token

    // Create an AccessManager to manage our Access Token
    var accessManager = new Twilio.AccessManager('$TWILIO_ACCESS_TOKEN');
    
    // Create a Conversations Client and connect to Twilio's backend
    conversationsClient = new Twilio.Conversations.Client(accessManager);
    conversationsClient.listen().then(function() {
        console.log('Connected to Twilio!');
    }, function (error) {
        console.log('Could not connect to Twilio: ' + error.message);
    });
    

There is further information at The Twilio Video Docs and more information on working with conversations here

Rachel Gallen
  • 27,943
  • 21
  • 72
  • 81
  • more comprehensive docs here http://twilio-php.readthedocs.io/en/latest/usage/token-generation.html – Rachel Gallen Jun 27 '16 at 19:47
  • Hi Rachel, thanks for offering your assistance here. Can I send you a t-shirt to say thanks? Email mspeir@twilio.com. – Megan Speir Jun 27 '16 at 21:00
  • @MeganSpeir haha Megan, i hope it's free :) i may just take you up on that! lol – Rachel Gallen Jun 27 '16 at 21:37
  • 1
    Thanks @RachelGallen but this code is for Audio call , i am implementing video call functionality, and guys i have solved issue with help of customer center, the actual problem is of server timezone, so it was giving me error in `"nbf": 1466743969`. I have put the latest version of AccessToken.php here and it will work. Thank you all for your help and time :) – Brijal Savaliya Jun 28 '16 at 07:28
  • @MeganSpeir T-shirt for me ? :) – Brijal Savaliya Jun 28 '16 at 07:33
  • 1
    Hey Brijal, seems as though Rachel edited her answer for the Video guide. But if you want to post your solution in an answer too that would be great. Email me, mspeir@twilio.com for t-shirt info. Cheers! – Megan Speir Jun 28 '16 at 16:09
  • I have update my answer in my question .. :) Thanks for your time and efforts!! – Brijal Savaliya Jun 29 '16 at 12:56
  • Any suggestions on the below question ?http://stackoverflow.com/questions/41498841/trigger-an-incoming-voip-call-using-callkit-and-twilio-video-api – SpaceX Jan 06 '17 at 04:52
  • can someone please advise me on a similar issue http://stackoverflow.com/q/41709800/2534233 – SpaceX Jan 18 '17 at 07:30
0

I'v got solution of this issue with the help of Support.

Solution

In my old version of /Services/Twilio/AccessToken.php , I have an attribute "nbf": 1466743969(not-before time), which means it is not valid until 04:52:49 UTC. However according to the timestamp in the log file it was 04:50:27 UTC (10:20:27 IST)`. If the system clock of the server generating the access token is a couple minutes fast it will result in an invalid not-before time.

Later versions of the twilio-php library omitted the "nbf" attribute by default, because of this clock skew issue. If you get the latest version of AccessToken.php here:

https://github.com/twilio/twilio-php/blob/master/Services/Twilio/AccessToken.php

it will generate access tokens without "nbf".

An alternate fix would be to make sure the server time is accurate, but you would need administrator access to adjust it.

Brijal Savaliya
  • 1,101
  • 9
  • 19