ApiRTC Access token : Using JSON Web Token (JWT) for session authentication

ApiRTC Access token : Using JSON Web Token (JWT) for session authentication

We often receive questions about tokens. Tokens are used to authenticate each endpoint to the ApiRTC platform service and enable sessions. We’ll answer some frequently asked questions regarding tokens in this article

 

What is a token?

   

Access tokens are short-lived tokens that can be used to authenticate ApiRTC clients. There are created on the server to grant access to client API features. All tokens have a limited lifetime, configurable up to 24 hours. However, it is recommended to generate tokens with the shortest lifetime suited to the application.  

 

What are the benefits of token-based authentication?

 

Token-based authentication is very secure and extremely flexible.

 

Tokens are a way for you to authenticate your users in the ApiRTC platform without sharing any end-user information. Once you have authenticated your users you can decide when to permit them to join a video session.

 

Overview

 

The authentication call-flow is illustrated below:

Access tokens are generated on the server and uses then to authenticate with ApiRTC. Each token is a JWT (JSON Web Token) which is an encoded JSON object containing all grants.

 

JSON Web Token

 

JSON Web token is an open standard defining a compact and self-contained way for securely transmitting information between parties as a JSON object.

 

This information can be verified and trusted because it is digitally signed. When tokens are signed are signed using private/public key pairs, the signature also certifies that only the party holding the private key is the one that signed it.

JSON Web Tokens are particularly useful in the following scenarios:

 

  • Authorization: This is the most common usage. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access services permitted with that token. SSO (Single Sign On) is a feature using widely JWT for instance, because of its ability to be easily shared between different domains.  
  • Information Exchange: JSON Web Tokens are a good generic way of securely transmitting information. JWTs can be signed and additionally as the signature is calculated using the header and the payload, you can also verify that the content has not been tampered with.

 

JSON Web Token structure

 

In its compact form, JWT consists of three parts (header, payload and signature) separated by dots. It typically looks like:

 

xxxxx.yyyyyy.zzzzzz

 

Header

 

The header is usually composed of two parts: the type of the token (which is JWT) and the hashing algorithm used (such as HMAC SHA256).

 

For example:

{
  "typ": "JWT",
  "alg": "HS256"
}

 

Then this JSON is base64 (URL variant) encoded to form the first part of the JWT.

   

Payload

 

The second part of the token is the payload, which contains the claims. Claims are statements about an entity (the user) and additional data. There are three kinds of claims: registered, public and privateclaims.

 

  • Registered claims: these are predefined (not mandatory but recommended) providing a set of useful and interoperable claims. They are iss (issuer), sub (subject), aud (audience), exp (expiration time), nbf (not before), iat (issued at) and jti (JWT ID).
  • Public claims: they can be defined at will and should be registered at the IANA or defined with a URI namespace to avoid collisions.
  • Private claims: custom claims to share information between parties that agree on using them.

 

An example payload is:

 

{
  "iss":"joe",
  "exp":1300819380,
  "userId": "b08f86af-35da-48f2-8fab-cef3904660bd"
}

 

The payload is then base64 encoded to form the second part of the JSON Web Token.

 

Signature

 

The signature is then created using the encoded header, the encoded payload, a secret with the algorithm specified in the header.

 

For example, with HMAC SHA256, the signature is as follows:

 

HMACSHA256(base64Encode(header)>HMACSHA256(base64Encode(header) + "." + base64Encode(payload), secret)

 

The final output is three base64 strings separated by dots that can be easily transferred in HTML and HTTP environments.

 

The JWT for the previous header and payload is:

 

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJqb2UiLCJleHAiOjEzMDA4MTkzODAsInVzZXJJZCI6ImIwOGY4NmFmLTM1ZGEtNDhmMi04ZmFiLWNlZjM5MDQ2NjBiZCJ9.fqfYXdl1ePptXbqj3_r4kAS3i2pXImt8vzYsYqcAkZM>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJqb2UiLCJleHAiOjEzMDA4MTkzODAsInVzZXJJZCI6ImIwOGY4NmFmLTM1ZGEtNDhmMi04ZmFiLWNlZjM5MDQ2NjBiZCJ9.fqfYXdl1ePptXbqj3_r4kAS3i2pXImt8vzYsYqcAkZM

 

How to generate a token sample?

 

Following source code shows you how to create the access token needed for your ApiRTC user’s authentication on a node.js server. This sample can easily be adapted on all Web server.

 

We will use jsonWebToken module available on npm in this sample:

 

npm install jsonwebtoken

 

AccessToken.js describe the token generation and the needed parameters:

 

File AccesToken.js

 

const jwt = require('jsonwebtoken');
const uuidv4 = require('uuid/v4');

function AccessToken(apiKey, secret, options) {
    if (!apiKey) {
        throw new Error('apiKey is required');
    }
    if (!secret) {
        throw new Error('secret is required');
    }
    options = options || {};

    this.apiKey = apiKey;
    this.secret = secret;
    this.audience = options.audience || 'apiRTC';
    this.ttl = options.ttl || 3600;
    this.identity = options.identity;
}

AccessToken.ALGORITHM = 'HS256';
AccessToken.prototype.toJwt = function() {
    let payload = {
        grants: {
            identity: this.identity
        }
    };

    return jwt.sign(payload, this.secret, {
        header: {
            typ: 'JWT'
        },
        algorithm: AccessToken.ALGORITHM,
        subject: this.apiKey,
        audience: this.audience,
        expiresIn: this.ttl,
        jwtid: uuidv4()
    })
};
module.exports = AccessToken;

 

Needed parameters in our JWT are:

 

  • Subject: value is your apiKey
  • Audience: value must be 'apiRTC' or an array containing 'apiRTC'
  • expiresIn: value of the token expiration
  • jwtid: value must be a universal unique identifier
  • algorithm: value must be HS256'

 

Here is the code to generate and verify the token, mainly using apiKey and the secret:

 

File main.js

 

const AccessToken = require("./AccessToken.js");
const jwt = require('jsonwebtoken');

const VERIFY_DELAY = 1000;

const apiKey = 'fd4ed241d2b2769a285d154f4efc9f87';
const secret = 'U5EO74ZX7e3BMjsmtFXyt651';

let token = (new AccessToken(apiKey, secret, {identity: 'roger', ttl: 7200})).toJwt();
console.log('token: ' + token);

setTimeout(() => {
    console.log(jwt.verify(token, secret, {algorithms: ['HS256']}));
}, VERIFY_DELAY);

 

How to generate a secret key generation on cloud.apirtc.com?

 

Secret key can be activated and generated on your ApiRTC dashboard. Connect with your account on cloud.apirtc.com and then select the credential menu:

 

 

You can now activate and manage your secret key configuration:

 

Need some help?

 

If you have questions with this feature, we are happy to help, contact us on chat or post your support request on stackoverflow.

Get your API key