Authentication process

This guide will help you manage the authentication process and token refresh

Step 1: Obtaining an API Token

To access our API services, users must first obtain an API token by making a POST request to api.waldo.ai/authentication. The request should include two parameters in the request body:

apiKey: Your unique API key.

clientSecret: Your client secret.

Authenticate your account

POST https://api.waldo.ai/authenticate

Request Body

A successful request will return a JSON Web Token (JWT) in the response. This JWT token will be used to authorize your subsequent API requests.

View the authentication request in detail in the API Reference section.

Step 2: Authenticating API Requests

Once you have obtained your JWT token, you should include it in the Authorization header of every API request you make. Set the header value as follows:

Authorization: Bearer your-jwt-token

This header informs our API that you are an authorized user, allowing you to access the requested resources.

Token Refresh Process

To ensure uninterrupted access to our API services, you should be aware of token expiration and refresh your token as needed.

Token Expiry

Tokens issued by our API have a one-hour expiry period. After this period, the token becomes invalid, and you will need to obtain a new one to continue accessing our services.

Automatic Token Refresh

After each successful API request, our API will include a new JWT token in the response headers. More precisely, you will find the new token in the Authorization header.

This token is generated automatically by our system and is used to refresh your current token.

To make use of this feature, it is recommended that you verify the expiration date of your token with each API request. If your token is about to expire, simply use the new token provided in the response header to replace the old one in your subsequent requests.

Example

Here's an example of how you can handle token refresh:

  1. Make an API request with your current token.

  2. Check the response headers for a new token (Authorization: Bearer new-jwt-token).

  3. Replace your old token with the new one in subsequent requests.

Here's an example in Node.js using ESM (ECMAScript Modules) to demonstrate how to refresh the token after each API request.

First, make sure you have Node.js installed with support for ESM. You can create a JavaScript file (e.g., api.js) with the following code:

// Import the necessary modules - axios and form-data may need to be installed, or you can use your own HTTP client
import axios from 'axios';
import FormData from 'form-data';
import jwt from 'jsonwebtoken';

// Initialize your API key, client secret, and initial token
const apiKey = 'YOUR-API-KEY';
const clientSecret = 'CLIENT-SECRET';
const apiRoot = 'https://api.waldo.ai';
let currentToken = null;

// Function to refresh your token
const refreshToken = async () => {
    try{
        // Make a request to the API to refresh your token
        const data = JSON.stringify({
            apiKey: apiKey,
            clientSecret: clientSecret
        });

        const response = await axios.request({
            method: 'post',
            url: `${apiRoot}/authenticate`,
            headers: {
                'Content-Type': 'application/json'
            },
            data: data
        });
        // Update the current token
        currentToken = response.data.token;
    }catch(error){
        console.log(error);
    }
};

const testToken = async () => {
    try {
        // Verify the token with the secret key
        const decodedToken = jwt.verify(currentToken, clientSecret);

        // Check the 'exp' claim in the decoded token
        const { exp } = decodedToken;

        // Get the current timestamp in seconds
        const currentTimestamp = Math.floor(Date.now() / 1000);

        // Compare the expiration timestamp with the current timestamp
        return exp && exp > currentTimestamp;
    } catch (error) {
        // Token is invalid or has expired
        return false;
    }
};

// Function to make an authenticated API request
const makeAuthenticatedRequest  = async () => {
    try {
        // Check if we have a valid token or obtain a new one
        if (!await testToken()) {
            await refreshToken();
        }

        const response = await axios.request({
            method: 'GET',
            url: `${apiRoot}/some-endpoint`,
            headers: {
                'Authorization': `Bearer ${currentToken}`,
                'Content-Type': 'application/json',
            },
        });

        if (response) {
            // Handle the successful response here
            const responseData = response.data;
        } else if (response.status === 401) {
            // Token expired, obtain a new one and update currentToken
            await refreshToken();
            return makeAuthenticatedRequest(); // Retry the original request
        } else {
            throw new Error('API request failed');
        }

        // Check if there is a new token in the response headers
        const newToken = response.headers.get('Authorization');
        if (newToken) {
            currentToken = newToken; // Update currentToken
        }
    } catch (error) {
        throw 'Error making an API request: ' + error.message;
    }
};

await makeAuthenticatedRequest();

Note: replace in the code above /some-endpoint with the appropriate endpoint.

Last updated