How To Authenticate With JSON Web Tokens For Interactive Live Streams

Devin Dixon
BingeWave

--

While BingeWave makes it easy to implement live streams, one of the most important features is the ability to authenticate a user. Authentication is more than just security; it gives the user an identity that can be used to tailor experiences for them and help your app deliver highly customized features.

This tutorial will go over how authentication works with your Organizer account and how to associate a user with BingeWave’s interface.

Code And Requirements

Please read the information below on how to download the code and the developer requirements.

Developer Requirements

To create this app, we will be using the following tools and ask that the developer already know the basics of:

  • Command Line
  • React Native
  • Expo
  • Express

Download The Code

The code in this tutorial is available online at our Github repository and can be downloaded and ran on your local computer. To get the code, please visit:

https://github.com/BingeWave/Authentication-With-JSON-Web-Tokens

Organizer Account

Like all of our tutorials, our starting point will be an organizer account. This will allow you to access all our API features. Please read the tutorial on Setting up an Organizer Account if you have not already; it should only take a minute or two.

Why Is Authentication Necessary

When BingeWave features are embedded into your website or mobile app, our app does not know who the user is. Without knowing who a user is, you cannot do customization and personalization, such as putting the user’s name at the bottom of the video chat.

In our Live Streaming API, we provide several key features that must be associated with a user for the functionality to work correctly. This includes elements such as:

  • Permission Control: Widget activation, layout types, chat, and other features require a user to grant or deny permission.
  • Tracking: Every action on the platform is recorded and requires a user to associate actions with.
  • Display Information: Many widgets will display information such as a first name, last name, avatar, and other personalized information.

Authentication of a user is required for you to customize and personalize their experience. You will need an organizer access token discussed in the next step to execute authentication.

Organizer Access Token

Before you can authenticate a user, you will need an organizer access token. The organizer token is a special token that grants super-user access to all elements of your account. Therefore, this token must be kept secured and should ONLY be used for server-to-server communication.

To get your organizer access token, go to the list of your organizer accounts here:

https://developers.bingewave.com/organizers

Click on the ‘Tokens’ button to be brought to your tokens screen. If none exist, click into tokens either create a new token or select a current one.

Remember this token because you will need it in several steps throughout this tutorial.

Getting A Users JWT Token

When developing your application, you will have to sync your users with BingeWave. Syncing a user means that you will have your database with your users, and you will sync specific information with BingeWave about the user to get a JSON Web Token (JWT). The JWT will allow the synced user to interact with BingeWave’s features.

Luckily, syncing a user with your account is easy. Our API has two specialized functions called registerToOrganizer and loginToOrganizer for syncing the data.

registerToOrganizer

The authentication route will create a new user from your database and associate with your BingeWave account. The documentation for registering a user is located here:

https://developers.bingewave.com/docs/auth#registertoorganizer

The required fields are:

  • Organizer Auth Token
  • First Name
  • Last Name
  • Email

To test the function, we are going to use the Query Builder. The Query Builder is a way of running queries against the API without writing code to test the service. Header over the Query Builder At:

https://developers.bingewave.com/queries/auth#registertoorganizer

In the Body Params, enter a first_name, last_name, and email:

And in the Authorization Tab, replace your Auth Token with the Organizer Token retrieved above.

Now when you click ‘Send’, and user successfully registers to the organizer, you will receive an auth token for that user.

Next, let us look at the login function.

loginToOrganizer

The login function is used to retrieve an auth token for a user already registered with your organizer account. The documentation for logging in a user is located here:

https://developers.bingewave.com/docs/auth#logintoorganizer

The only two values that are required are the following:

  • Organizer Access Token
  • Email Address

The password is not needed because this should be used as a backend service on your service only to retrieve that auth token for BingeWave. To log in and retrieve the users token lets head over the Query Builder and test out the API endpoint at:

https://developers.bingewave.com/queries/auth#logintoorganizer

Like the previous step, change your Authorization token to the organizer token.

And then enter the email used to log in. This only requires an email and not a password because it assumes you have authenticated the user on your service and only want to retrieve their JWT for BingeWave.

A result should return with the user’s auth token. You are doing great! The next steps in this tutorial will create a sample backend for authenticating that we will use for web and mobile applications.

Backend Example

The Organizer Token is very powerful and dangerous. This should NEVER be exposed to the front end and always be kept in a secure location. Therefore, we will create an example backend that simulates how all frontend applications (website and mobile) should interact with a backend to retrieve a JWT Token.

On your command line, let us start by making an example project:

mkdir auth_examplecd auth_example

This folder now serves as the root directory for your application. Next, we are going to make a few folders. We will have a backend server, web application, and React Native application to represent three different areas of the application. Let us make the folders for each of those.

mkdir backendmkdir webmkdir mobile

For our backend, we will keep it very simple with an Express server. If you are new to Express, Express is a very simple NodeJS HTTP server to setup. Go into the folder and create an express application.

cd backendnpm initnpm i --save expressnpm i --save dotenvnpm i --save axios

When npm init is setting up the project, make the entry file server.js. We will specify this file later.

To briefly summarize the above console commands, with NodeJs, we have installed the express web server, dotenv will be used to retrieve environment variables stored in a .env file, and Axios will be used to send HTTP requests.

Next, we are going to create a .env file.

touch .env

This file will store environment variables. The .env file should NOT be stored in a repository but injected into the server by another service. In our .env file, we are going to store our organizer token. With your favorite editor, put the following inside the .env file:

ORGANGIZER_TOKEN=xxxxxxxx

Replace the xxxxxx with the organizer token value retrieved in our previous step. Now let us work on our server to create the main file.

touch server.js

And with your favorite editor, start to add the following:

//Require the need files
const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const axios = require('axios')
//Set the listening port
const port = 3500;
//Create the express app
const app = express();
//Add configuration options
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use(cors());
//Enable Dot env
dotenv.config();
//Start the server
app.listen(port, () => { console.log(`Example class app listening at http://localhost:${port}`) })

The above code sets up our basic express application to act as our backend. The app uses dotenv to get the environment variable, and we are enabling cors to allow browser apps to connect to the backend. Now we have to define one of the two routes the register. Start by creating a basic route in Express:

In the above code, the following happens:

  1. We set the register route in Express to listen to a POST request.
  2. We set the URL to the API endpoint.
  3. We retrieve the Organizer token from the .env.
  4. We use Axios to make a request to BingeWave’s API.
  5. We return the JSON result from the BingeWave API to the device that called our backend.

In a similar design, the login route looks as such:

This code ONLY serves as an example. The user should first register with you in a production environment, save their information to your database, and then sync with BingeWave’s API. Now let us build out a browser app and then React Native App.

Create A Live Event

Before we get to the applications, we need something to showcase a live stream or video chat. Everything in BingeWave (live stream, video chat, AR Session, etc.) is considered a Live Event. We are quickly going to create a live event using the Query Builder. First, we need an event type, which can be checked here:

https://developers.bingewave.com/types#event_types

We want a very quick setup, so let us choose an Instant Event which as a value of 7. The other event types are all scheduled, and require a date/time. Now we can head over to the Query Builder for creating a live event and plug in the information:

https://developers.bingewave.com/queries/events#create

Make sure that you use the organizer id associated with the organizer token used above.Click the ‘Send’ button to create the Live Event.

When the result returns, there are a few key fields to pay attention to:

  • id: The id of the live event. Remember this as we will use it a lot in the upcoming steps.
  • embed_script_tag: This field is a script tag that will go into HTML pages. It is used to parse tags.
  • embed_video_chat: This field is a tag that is used to embed the video chat feature into HTML web pages.
  • webview_video_chat: This field is a URL of the video chat that goes into webviews, primarily used in mobile apps.

Now that we have our live event data, we can build our authentication application. Save the data as we will use in the following steps.

Browser App

We will build a very simple HTML app to showcase how to use the Authentication tokens. For HTML Web Pages, BingeWave uses a tag system described here:

https://developers.bingewave.com/javascript/bwconnector

To describe the above, BingeWave’s Library will parse widget tags as such:

<bw:widget></bw:widget> 

These tags on a webpage and turn into an interface for your users on the page. It starts by implementing the connection in a script tag in your HTML:

<script type=”text/javascript” src=”https://connect.bingewave.com/connect.js"></script>

And then we have to init the Connector script like this:

<script type=”text/javascript”>
BingewaveConnector.init({auth_token : “xxxx”});
</script>

The auth token should be the JWT return from the user in the previous steps when a user registers or logs in. Finally, we need the widget that we want to display to appear on-screen. Refer to the embed_video_chat returned from the Live Event JSON, and that will go in the HTML as such:

<bw:widget env=”prod” type=”webrtc” id=”xxxxxx”></bw:widget>

The xxxxx value should be replaced with your event ID. The final result of your web app should look like below:

The code is fairly straight forward with basic HTML, we are utilizing Bootstrap for basic design, and implement the script and tag. Now using the token, the user will be authentication and logged in with the current video chat loaded on-screen.

getUserMedia Undefined Error

On your local host in your web browser, you might run into this issue:

What is happening is the your browser is block the ability to get the video because it is not a secure connection. To solve this error, read this article here on WebRTC Fix For getUserMedia Undefined On Local Hosts.

React Native

For the final part of this tutorial, we are going to focus on React Native, Webviews, and Authentication. In our project, go to the root directory, and type the following:

expo init mobile

Choose the bare minimal app and let the installation run. After it has run, go into the mobile folder and install the following packages:

cd mobilenpm install --save react-native-webviewnpm install @react-navigation/native @react-navigation/native-stack --saveexpo install @react-native-async-storage/async-storageexpo install react-native-screens react-native-safe-area-context

To summarize the installation, we have installed:

  • react-native-webview for showing a webview of a website in our app.
  • async-storage for storing persistent data.
  • react-navigation for switching between screens.

Make sure that run the pod installs for iOS:

cd iospod installcd ..

In our application, we are going to have four screens:

  1. Home Page for deciding to either login or register
  2. Register Page for signing up
  3. Login Page for logging in
  4. Video Page for joining a web conference

Let us make those screens below:

mkdir screenstouch screens/Login.jstouch screens/Register.jstouch screens/Home.jstouch screens/Video.js

Home Screen

First, we will handle the Home Screen for deciding if a user should log in or register. In your editor, open up Home.js and input the following:

The code is very basic React Native code. This is not a React Tutorial, and we expect the developers reading this tutorial to have a basic understanding of React Native. In the code, we pass in the navigation object passed from the parent and will be used for switching screens. The view is two buttons that will either go to the login page or register page using the navigation object when clicked.

Register Page

The register page is where the user will register. We will call the backend application we defined before. The code for the registration page is below:

To break down the important parts of the code:

  1. We are using useState Hooks to set the email, first_name, and last_name values.
  2. The attemptRegister will use fetch for making a call the API we defined in the previous step and pass the data from the useState hooks to the API.
  3. On successful registration, we are storing the values in AsyncStorage so we can access the auth token throughout the app, and the navigation object will take the user to the next page.
  4. The form is back to React Native elements that utilize useEffect for updating the typed value.

Login Page

The login page is very similar to the Registration page. It will also call the backend defined in the previous step.

The login code breaks down as such:

  1. We are utilizing the useState hook to set the email that will be used for logging in
  2. Fetch is calling the API login endpoint defined in the previous step and sending the email to the endpoint
  3. On a successful response, store the auth token from the JSON into Async storage and navigate to the watch page
  4. The rendering of the view is just basic React Input that changes the state of the email when a user types into it

Video Page

For the final page, we have the Video page, which will allow a user to join the video chat. In this video page, we want the user to join the video chat using their account associated with BingeWave, and not an anonymous user. We are going to use our auth token to make sure the user session is used as such. The code for achieving that is below:

To summarize this code:

  1. When the function is loaded, we call the auth token we stored in the AsyncStorage during login or registration.
  2. We take the webview_video_chat URL and use that as the src for a Webview
  3. In the Webview, we also pass in the headers the token as an Authorization header

Now when the user joins the webview, they will be authorized and logged in as the user associated with the auth token.

Applying Authentication To More Use Cases

This tutorial covered how to do authentication in React Native and Web Apps. But there are a variety of different technologies ranging from Swift to Flutter for developing the solutions. The key takeaways from this tutorial that are re-usable in other solutions are:

  1. Authentication into an organizer account requires an organizer token
  2. The organizer token should be kept in a secure location and never publicly exposed.
  3. Access to registering and logging a user through the organizer routes should only be done on the server-side.
  4. Auth tokens must be passed as an Authorization header to log the user into an embedded BingeWave widget.

--

--