Securing your Millicast Viewer

Create an API Token

In this tutorial we will be using the Millicast API. Before you make an API call you must first create/get your API Token from the account section in the Millicast dashboard.

Log into the dashboard and click on the Account button from the left main menu. Under the Security section find the API Secret and copy it. If this is the first time using the API the field will first create one for you.

We will use this token to authenticate our CURL calls to the API.

Create a Secure Publishing Token

Next, we must first create a rule in the Publishing Token that will only accept authorized subscribers. To do this you will need to change the "subscribeRequiresAuth" setting in the Publish Token to ‘true’. You can do a simple CURL call to create a new secure token which includes this setting, or update an existing token.

Open your terminal/command prompt on your computer and copy the CURL call below to create a new Publishing Token via the API (see API Docs for Publishing Token - Create)

NOTE:
Stream names are global to your account, which means each stream name MUST be unique or you can possibly override your broadcasts by accident._

Please add the API token to your CURL call. Also please include a unique stream name, and be sure to set the "subscribeRequiresAuth" setting to true, see below:

curl -H "Authorization: Bearer 3b9147acc166488b8220268a6bfcb06762b47b74cfe57fedc1208847de3a3de8" \
     -H "Content-Type: application/json" \
     https://api.millicast.com/api/publish_token \ 
     -d '{"label": "secure_viewer", **"subscribeRequiresAuth": true**, "streams": [{**"streamName": "unique2445"**}]}'

Hit enter to run your call, if all was setup correctly you will have a response containing the token information for publishing.

NOTE:
If you prefer to update an existing token instead of making a new one, you can do that with this update call: Publishing Token - Update )._

{  
  "status":"success",  
  "data":{  
    "subscribeRequiresAuth":true,  
    "Record":false,  
    "Id":252124,  
    "Label":"secure_viewer",  
    "Token":"253829644ef566cb85fc83940a1d01408f705fe52f78f9b33e509cb40cd82c00",  
    "addedOn":"2020-05-26T23:09:09.0809551Z",  
    "expiresOn":null,  
    "isActive":true,  
    "streams":[{"streamName": "unique2445","isRegex":false}]  
  }  
}

If you see the "subscribeRequiresAuth" setting set to true, then you have successfully secured the subscription to the broadcast. All viewers are now required to authenticate before they can watch your streams.

NOTE:
If you have your own publisher, or you are using OBS, you will need the "Token" and the stream name to broadcast.

For this demo we will be using the publisher in the dashboard. If you haven't already, please log into your dashboard and select "Live Broadcast", there you should see the token we just created in the list. Click on the broadcast button to open the broadcaster application. The next section will show you how to create a Subscribe Token for the viewer like we did for the Publisher Token.

Create a Subscribe Token

In order to properly authenticate a subscribing viewer we need to create a Subscribe Token from the API. To do that all we will need is the stream name we just created in the publishing token and another CURL call to the Millicast API.

curl -H "Authorization: Bearer 3b9147acc166488b8220268a6bfcb06762b47b74cfe57fedc1208847de3a3de8" \
     -H "Content-Type: application/json" \ 
     https://api.millicast.com/api/subscribe_token \
     -d '{"label": "allow_me", "streams": [{**"streamName": "unique2445"**}]}'

NOTE:
The call is very similar to creating a publishing token, however do not forget to use your API token we got in the beginning of this tutorial, and not the publisher token.

If your call was set up correctly you will get back the Subscribe Token we need to view the live broadcast to "unique2445" in the result.

{  
  "status":"success",  
  "data":{  
    "Id":44,  
    "Label":"allow_me",  
    "Token":"176949b9e57de248d37edcff1689a84a047370ddc3f0dd960939ad1021e0b744",  
    "addedOn":"2020-05-22T16:00:06.269683Z",  
    "expiresOn":null,  
    "isActive":true,  
    "streams":[{"streamName":"unique2445","isRegex":false}]  
  }  
}

If you did not take a note of this token and need to retrieve it later on, you can retrieve your sub tokens with the API using the List call (see API Docs for Subscribing Token - List).

We have what we need to start our protected broadcast.

Start the Secure Broadcast

Now that we have our tokens properly configured you can set up the authentication of your viewer. Once again go to your dashboard, and click on Resources from the left menu, find the Javascript SDK and download it, or click here.

We will be modifying the viewer.html code and using the dashboard broadcaster with the Subscribe Token.

Let us begin by editing the viewer with your account details. We will simply write them directly into the script for now.

At the top of the script tag you will see 2 variables labeled accountId and streamName, both have a dynamic setting that queries the URL data to get the information provided by its parameters.

const params = new URLSearchParams(document.location.search.substring(1));  
const accountId = params.get('accountId');  
const streamName = params.get('streamName');

Instead of overriding these queries we will simply add a condition for both variables keeping its dynamic properties above. Below add some simple conditions to override the variables if the values are null.

let params = new URLSearchParams(document.location.search.substring(1));  
let accountId = params.get('accountId');  
let streamName = params.get('streamName');  

if(accountId == null) accountId = 'AytHcQ';  
if(streamName == null) streamName ='unique2445';  
constoken = '176949b9e57de248d37edcff1689a84a047370ddc3f0dd960939ad1021e0b744';**

_NOTE:
To get your Account Id simply go to the dashboard, and click on "Live Broadcast" from the left main menu. Find the token we created and click on the settings button, open the API section and you can find the Account ID there.

[/hide/]: # (See Publish and Subscribe API section for more.)

I have also included a new variable called subtoken to hold our Subscribe Token for easy reference.

Within the same script tag, below find a method named "updateMillicastAuth". This is where we authenticate and get our broadcast information, however if we were to run it as is against our secure broadcast it will deny access. The reason is we have not yet added the secure token needed to authenticate us correctly.

// gets server path and auth token.  
function updateMillicastAuth() {  
  console.log('updateMillicastAuth at: ' + apiPath + ' for:', streamName, ' accountId:', accountId);  
  return new Promise((resolve, reject) => {  
    let xhr = new XMLHttpRequest();  
    xhr.onreadystatechange = function (evt) {  
      if (xhr.readyState == 4) {  
        let res = JSON.parse(xhr.responseText);  
        onsole.log('res: ', res);  
        console.log('status:', xhr.status, ' response: ', xhr.responseText);  
        switch (xhr.status) {  
          case 200:  
            let d = res.data;  
            jwt = d.jwt;  
            url = d.urls[0];  
            resolve(d);  
            break;  
          default:  
            reject(res);  
        }  
      }  
    }  
    xhr.open("POST", apiPath, true);  
    xhr.setRequestHeader("Content-Type", "application/json");  
    xhr.send(JSON.stringify({streamAccountId: **accountId**, streamName: **streamName**}));  
  });  
}

To pass the token we would just need to add an authorization header in our http call. This is very similar to how the broadcaster currently authenticates to publish a stream.

// gets server path and auth token.  
function updateMillicastAuth() {  
  console.log('updateMillicastAuth at: ' + apiPath + ' for:', streamName, ' accountId:', accountId);  
  return new Promise((resolve, reject) => {  
    let xhr = new XMLHttpRequest();  
    xhr.onreadystatechange = function (evt) {  
      if (xhr.readyState == 4) {  
        let res = JSON.parse(xhr.responseText);  
        onsole.log('res: ', res);  
        console.log('status:', xhr.status, ' response: ', xhr.responseText);  
        switch (xhr.status) {  
          case 200:  
            let d = res.data;  
            jwt = d.jwt;  
            url = d.urls[0];  
            resolve(d);  
            break;  
          default:  
            reject(res);  
        }  
      }  
    }  
    xhr.open("POST", apiPath, true);  
    **xhr.setRequestHeader("Authorization", `Bearer ${subtoken}`);**  
    xhr.setRequestHeader("Content-Type", "application/json");  
    xhr.send(JSON.stringify({streamAccountId: accountId, streamName: streamName}));  
  });  
}

Your viewer is now ready to watch your secure broadcast.

Please log into the dashboard once again and select "Live Broadcast" from the left main menu. Find the stream token you created and click the green Broadcast button to run the online broadcaster. Once your mic and camera are set up, click on Start Broadcasting to publish your live stream.

To run your viewer simply open your viewer html page in a browser window (must be SSL enabled) and if your viewer was set up correctly you will see your broadcast right away in your viewer. To test the security you can run another viewer without the authorization header to see it reject your request.

Like the publishing token, if you want additional security, you can set an expiration date as well giving a set window of time to use the token before it is no longer valid. You can also create multiple Subscribe Tokens for 1 broadcast with different rules.

Thank you and I hope this tutorial was useful. If you have any questions please contact Millicast support for assistance.


Did this page help you?