JWT Authentication

Secure API authentication guide

This documentation provides an overview of JWT (JSON Web Token) Authentication and demonstrates how to generate a JWT token and use it to authenticate API requests securely.

Prerequisites

Before you proceed, ensure you have the following:

  • An environment that supports JWT generation and API calls (e.g., a programming language or framework)
  • An account with a service that requires JWT authentication
  • Environment variables set up for the necessary credentials (e.g., organization ID and private key, both can be found in your Vapi portal)

Generating a JWT Token

The following steps outline how to generate a JWT token:

  1. Define the Payload: The payload contains the data you want to include in the token. In this case, it includes an orgId.
  2. Get the Private Key: The private key (provided by Vapi) is used to sign the token. Ensure it is securely stored, often in environment variables.
  3. Set Token Options: Define options for the token, such as the expiration time (expiresIn).
  4. Generate the Token: Use a JWT library or built-in functionality to generate the token with the payload, key, and options.

JWT Token Scopes

The generated JWT token can have one of two scopes: private or public. The scope of the token will determine the actions that can be performed using the token.

For example, it can be used to restrict which API endpoints the token can access.

As of writing, the only publicly scoped API endpoint is https://api.vapi.ai//call/web, which is used for Web Call creation. All other endpoints are privately scoped.

Example (generating a private JWT token)

1// Define the payload
2const payload = {
3 orgId: process.env.ORG_ID,
4 token: {
5 // This is the scope of the token
6 tag: "private",
7 },
8};
9
10// Get the private key from environment variables
11const key = process.env.PRIVATE_KEY;
12
13// Define token options
14const options = {
15 expiresIn: "1h",
16};
17
18// Generate the token using a JWT library or built-in functionality
19const token = generateJWT(payload, key, options);

Example (generating a public JWT token)

1// Define the payload
2const payload = {
3 orgId: process.env.ORG_ID,
4 // This is the scope of the token
5 token: {
6 tag: "public",
7 restrictions: {
8 enabled: true,
9 allowedOrigins: ["https://example.vapi.ai"],
10 allowedAssistantIds: ["1cbf8c70-5fd7-4f61-a220-376ab35be1b0"],
11 allowTransientAssistant: false,
12 },
13 },
14};
15
16// Get the private key from environment variables
17const key = process.env.PRIVATE_KEY;
18
19// Define token options
20const options = {
21 expiresIn: "1h",
22};
23
24// Generate the token using a JWT library or built-in functionality
25const token = generateJWT(payload, key, options);

Explanation

  • Payload: The payload includes the orgId representing the organization ID and the token object with the scope of the token.
  • Key: The private key is used to sign the token, ensuring its authenticity.
  • Options: The expiresIn option specifies that the token will expire in 1 hour.
  • Token Generation: The generateJWT function (a placeholder for the actual JWT generation method) creates the token using the provided payload, key, and options.

Usage (Making an Authenticated API Request)

If you set the scope to private, you can use it to make authenticated API requests. The following steps outline how to make an authenticated request:

  1. Define the API Endpoint: Specify the URL of the API you want to call.
  2. Set the Headers: Include the Content-Type and Authorization headers in your request. The Authorization header should include the generated JWT token prefixed with Bearer.
  3. Make the API Call: Use an appropriate method to send the request and handle the response.

Example

1async function getAssistants() {
2 const response = await fetch("https://api.vapi.ai/assistant", {
3 method: "GET",
4 headers: {
5 "Content-Type": "application/json",
6 Authorization: `Bearer ${token}`,
7 },
8 });
9
10 const data = await response.json();
11 console.log(data);
12}
13
14fetchData().catch(console.error);

Explanation

  • API Endpoint: The URL of the API you want to call.
  • Headers: The Content-Type is set to application/json, and the Authorization header includes the generated JWT token.
  • API Call: The fetchData function makes an asynchronous GET request to the specified API endpoint and logs the response.

Usage (Web Client)

If you set the scope to public, you can use it to make authenticated API requests using the Vapi Web Client.

import Vapi from '@vapi-ai/web';
const vapi = new Vapi({
token: 'your-jwt-token',
});
vapi.start('your-assistant-id');

Notes

  • With the generated token, you can authenticate API requests to any endpoint requiring authentication. The token will be valid for the duration specified in the options (1 hour in this case).
  • If you don’t specify token in the JWT payload, the token will be public.

Conclusion

This documentation covered the basics of generating a JWT token and demonstrated how to use the token to make authenticated API requests. Ensure that your environment variables (e.g., ORG_ID and PRIVATE_KEY) are correctly set up before running the code.