Generating Tokens without Server Side SDK

During AngelHack, Alexander Ramirez came up to me with a puzzle. “How do I generate sessions and tokens?” He asked. Normally, I would have told him to use one of our server side SDKs, but he was building a browser plugin with video chat and wanted to use our REST API instead. Getting the SessionId is easy, it’s a simple POST request. However, generating token is not so straightforward because it is generated algorithmically. This tutorial will show you how to generate a token, and examples used here will be written in JavaScript.

Tokens are base64 encoded string with the following data fields: partner_id, sig, session_id, create_time, expire_time, role, connection_data, and nonce.

First, let’s generate the simple fields.

session_id can be created by sending a post request to our server.

Create_time is stored in seconds so we need to write Date.now()/1000

expire_time can be set set to 24 hours (86400 seconds) from today, so it’s value is create_time + 86400

role if I want my user to be able to record the session and force others to disconnect, I would put ‘moderator’ here

connection_data We can put in the user name for data, which in this case can just be “bob”

nonce is a random number, Math.floor( Math.random()*99999 )

The trickest value to generate is the sig key, which is used to verify these token values. To generate this encrypted signature, we need to use Keyed-hash message authentication codes. Fortunately, there is a javascript library called Crypto that let’s us do just that.

We will use progressive HMAC Hashing, so we will first need to generate a HMAC object with our secret, pass in our token values, and then finalize the HMAC.

var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, "Secret Passphrase");
hmac.update("session_id="+sessionId+"&create_time=...");
var hash = hmac.finalize();

If you now print out this sig as a string, it should look something like this: 58ceea3adfd277c02545e3eaef23dfcf94496803

Now time to put all these values together into one string:

"partner_id=...&sig=...:session_id=...&create_time=...&expire_time=...

Base64 encode this new string and then add the “T1==” to the beginning of the encoded string. You can now use this token to authenticate yourself to that specific session.

Here’s the full code

With that said, please be aware that you should never expose your secret in your client side code due to security concerns.

Thanks for reading,

Song

  • Nick

    Thanks, Song. This is really helpful. One question that I could probably figure out myself but thought I would just ask on here in case others are looking for the answer: How is this done using the iOS SDK? I would think that generating the sig key would be done differently if nothing else. One other thing that could be useful is a tutorial for integrating with mobile backend solutions like Parse, which are becoming increasingly common.