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 )
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:
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,