<img src="https://certify.alexametrics.com/atrk.gif?account=bIEZv1FYxz20cv" style="display:none" height="1" width="1" alt="">

Get a JWT

 

A JSON Web Token, or JWT, authorizes your application code to securely connect to your unique Spatial Audio API Space.

Project Complexity: ★★☆☆☆

JWTs are an open industry standard method for securely representing claims between two parties. Click here to learn more about JWTs. (Link will open in a new tab)

In this guide, you will learn how to:

  1. Sign up to use the Spatial Audio API
  2. Create a High Fidelity Spatial Audio App and a Space to use for our tests
  3. Get a Test JWT used to authorize your test applications with High Fidelity
  4. Programmatically generate a JWT

1. Sign Up to Use the Spatial Audio API

 

If you already have a High Fidelity Developer Account, you can jump straight to the next step.

Before your app can make use of the Spatial Audio API, you'll need a High Fidelity Developer Account. Sign up for an account or log in here.

 

2. Create an App and Space for Testing Purposes

No matter the method you use to generate a JSON Web Token for use with the Spatial Audio API, you will need to first create an App, then at least one Space associated with that App. To do that:

  1. Log in to your High Fidelity Developer Account.
  2. Under "New App Name", enter an app name.
    • Example: "My Test App"
  3. Click the "Create New App" button.
  4. On the page that appears, under "New Space Name", enter a space name.
    • Example: "My Test Space"
  5. Click "Create New Space".

Do not share the data you see on this page. It allows users to make authorized connections to your High Fidelity Spatial Audio Server.

 

 

Method 1: Get a Test JSON Web Token

It can be useful to obtain a test JWT to make sure that your test applications can connect to the Spatial Audio API Servers.

Do not use Test JWTs generated using this method for production applications. To learn how to generate JWTs for production environments, skip to the next step.

To get a Test JWT:

  1. Log in to your High Fidelity Developer Account.
  2. On the "Account Overview" page, click on the app name that you created in Step 2 above.
  3. On the "App Details" page, click on the name of the space that you created in Step 2 above.
  4. On the page that appears, under "Optional User ID", enter a User ID.
      Example: "Test User 01"
  5. Click the "Make Test JWT" button.

The long string that is generated is your Test JSON Web Token (JWT). You can use this Test JWT for testing your applications, such as the one you can build by following the "Build a Simple Web App" guide.

Do not share this JWT. It allows users to make authorized connections to your High Fidelity Spatial Audio Server.

Your JWT should look something like this sample JWT (this sample won't work in any of your apps):

NYCytIANhIiUQL9OeBYfUWZuLxiQtclLOGyV31Z0YIjTCCnIJ106RX06Q79Mjt1kcXMVMMINyZNCjeDsflmCIDMTmdcNz0ieRxbY.ZMwlZTJXkBOn.ZVU0ZzNalLipDJ3L5niFQnYZ5aFGt7JC2TlWiJJOMw33IICaiDcQinWMpGizhjTjLjR9yQjJ004OmJCIVfwyWZZjmII8FhlLSjV2TIHOil61DEUNi-VWUzM5Ms

 

Method 2: Generate a JWT Programmatically

In your application's production environment, each client running your app code should connect to the High Fidelity Spatial Audio Server with a unique JWT.

 

In the case of a Web application, your application server code should generate a JWT associated with the user requesting your Web application. There is almost certainly a library available for your server's language - check out jwt.io/#libraries-io to find a library relevant to you.

 

We recommend that your production application create JWTs with an expiration time. A JWT without an expiry value can be re-used as the API has no way of knowing if it is a legitimate JWT or a stolen JWT. Once the expiration time has passed, the token is no longer valid. Common practice is to make the expiry time relatively short - ~15 minutes - so that any compromised JWTs will cease to be valid quickly.

 

We have learned that the High Fidelity API uses JWTs to authenticate and direct incoming connections into your Spaces. These JWTs are generated by making use of the following pieces of information:

  • Your Application's UUID
  • Your Space's UUID
  • An App Secret known only to you and High Fidelity, used to sign the JWT
    • The App Secret is set at the App level, so you can use the same App Secret across all Spaces within that App.
  • (Optional) A "User ID" string defined by your application that can be used to identify a particular user's connection

You can find all of this information in the High Fidelity Audio API Developer Console. There, after creating a new App and Space as in Step 2 above, you will find a screen that looks like this:

An example App Details page.

Do not share the data you see on this page. It allows users to make authorized connections to your High Fidelity Spatial Audio Server. If you accidentally expose your App Secret, you can regenerate one from the App Details page in the Developer Console.

Next, we will detail how to generate a Spatial Audio API JWT using NodeJS. Before we dive in to the details, here's the most basic version of the NodeJS code used to generate a JWT:


const { default: SignJWT } = require('jose/jwt/sign');
const crypto = require('crypto');
try {
let hiFiJWT = await new SignJWT({
"user_id": USER_ID,
"app_id": APP_ID,
"space_id": SPACE_ID,
"admin": false
})
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.sign(crypto.createSecretKey(Buffer.from(APP_SECRET, "utf8")));
} catch {}

Method 2a. Set Up Your Local Development Environment

To complete this guide, you will need to install the following software on your computer:

Next, let's create a skeleton version of a NodeJS project we'll use for development:

Create a new folder on your local disk that you'll use for development, such as C:\code\hifi-get-jwt\. Then, install the JavaScript (NodeJS) version of the High Fidelity Spatial Audio Client Library by performing the following actions:

  1. Create a new folder on your local disk that you'll use for development, such as C:\code\hifi-get-jwt\.
  2. Using PowerShell or Terminal, cd into that development directory.
  3. Enter npm init to initialize a new NodeJS project, inputting data as prompted. The data you input isn't important for the purposes of this guide.
  4. Install the JavaScript (NodeJS) version of the High Fidelity Spatial Audio Client Library by typing npm install hifi-spatial-audio@0.6.1-6
      This will also automatically install the dependencies of the HiFi Client Library onto your system.
  5. Install jose with npm install josejose 
      is a package used to create JWTs using NodeJS.

Inside your development directory, create a new file called index.js. This is where we'll write our code.

 

Method 2b. Write the JavaScript code!

Now, we are going to write some NodeJS code! When executed, this code will create a new JWT, securely sign it, and then connect to the Spatial Audio API Server.

Open index.js in your favorite code editor.

Now, let's add to this file almost all of the code necessary to make this sample app work. Copy and paste the following code into index.js:




const { SignJWT } = require('jose/dist/node/cjs/jwt/sign'); // Used to create a JWT associated with your Space.
import { Point3D, HiFiCommunicator } from "hifi-spatial-audio";
const crypto = require('crypto');

// This is your "App ID" as obtained from the High Fidelity Audio API Developer Console.
const APP_ID = "aaaaaaaa-1111-bbbb-2222-cccccccccccc";

// This is your "Space ID" as obtained from the High Fidelity Audio API Developer Console.
const SPACE_ID = "aaaaaaaa-1111-bbbb-2222-cccccccccccc";

// This is the "App Secret" as obtained from the High Fidelity Audio API Developer Console.
const APP_SECRET = "aaaaaaaa-1111-bbbb-2222-cccccccccccc";

// Set this string to an arbitrary value. Its value should be unique across all
// clients connecting to a given Space so that other clients can identify this one.
const USER_ID = "steve";

async function start() {    
    let secretKeyForSigning = crypto.createSecretKey(Buffer.from(APP_SECRET, "utf8"));
    
    let hiFiSampleJWT;
    try {
        hiFiSampleJWT = await new SignJWT({
            "user_id": USER_ID,
            "app_id": APP_ID,
            "space_id": SPACE_ID,
            "admin": false
        })
        .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
        .sign(secretKeyForSigning);
    } catch (error) {
        console.error(`Couldn't create JWT! Error:\n${error}`);
        return;
    }
    
    const communicator = new HiFiCommunicator({
        position: new Point3D({ "x": 0, "y": 0, "z": 0 }),
    });

    try {
        let responseLogString = await communicator.connectToHiFiAudioAPIServer(hiFiSampleJWT);
        console.log(`Successfully connected to HiFi Audio API Server! Response:\n${JSON.stringify(responseLogString)}`);
    } catch (error) {
        console.error(`Couldn't connect to HiFi Audio API Server! Error:\n${JSON.stringify(error)}`);
    }
}

start();

Save your index.js file.

At this point, you'll need to find the App ID, Space ID, and App Secret associated with the App and Space that you created above.

Inside the index.js file, paste your App ID inside the quotes on the line const APP_ID = "aaaaaaaa-1111-bbbb-2222-cccccccccccc";. Do the same for your Space ID and App Secret.

Inside the index.js file, set a User ID inside the quotes on the line const USER_ID = "steve";.

In this example code, we are statically setting the user_id field of the JWT. In production environments, the user_id field of the JWT should be set dynamically based on the identity of the user using a given instance of your application.

Method 2c. Execute the JavaScript code!

Almost there! Let's run the code that we just wrote to make sure that it works.

  1. Using PowerShell or Terminal, cd into your development directory.
  2. Type node index.js and press enter.

If you see Successfully connected to HiFi Audio API Server! in the logs that appear, everything is working!

Conclusion

In this guide, you learned about JavaScript Web Tokens (JWTs) and how to use them with the Spatial Audio API. You created a Test JWT for debugging purposes, and created a simple NodeJS application that securely creates a JWT and connects to the Spatial Audio API Server.

For detailed technical information about the High Fidelity Spatial Audio Client API, visit the API documentation.

If you have any questions or comments, please reach out to support@highfidelity.com.