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:
- Define the Payload: The payload contains the data you want to include in the token. In this case, it includes an
orgId
. - 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.
- Set Token Options: Define options for the token, such as the expiration time (
expiresIn
). - Generate the Token: Use a JWT library or built-in functionality to generate the token with the payload, key, and options.
Example
Explanation
- Payload: The payload includes the
orgId
, representing the organization ID. - 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.
Making an Authenticated API Request
Once the token is generated, you can use it to make authenticated API requests. The following steps outline how to make an authenticated request:
- Define the API Endpoint: Specify the URL of the API you want to call.
- Set the Headers: Include the
Content-Type
andAuthorization
headers in your request. TheAuthorization
header should include the generated JWT token prefixed withBearer
. - Make the API Call: Use an appropriate method to send the request and handle the response.
Example
Explanation
- API Endpoint: The URL of the API you want to call.
- Headers: The
Content-Type
is set toapplication/json
, and theAuthorization
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
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).
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.