Refresh API Access Token

The token you receive from KORE, given your Client Credentials, will expire based on your settings. You must refresh the token, or your API calls will return errors.

To obtain a new access token, follow our guide, specifically Step 1 and Step 2.

The code samples provide examples for generating and managing OAuth2 tokens. They include methods to check if a token is expired and to fetch a valid token if the current one has expired.

const request = require('request');
const jwt = require('jsonwebtoken');

class TokenHelper {
  static async generateTokenHttp(clientId, clientSecret, url) {
    if (!clientId || !clientSecret) {
      throw new Error("Client Id or Secret is invalid");
    }

    const data = `grant_type=client_credentials&client_id=${clientId}&client_secret=${clientSecret}`;
    const options = {
      url,
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: data
    };

    return new Promise((resolve, reject) => {
      request(options, (error, response, body) => {
        if (error) {
          reject(error);
        } else if (response.statusCode >= 400) {
          reject(new Error(`Error in fetching token. ${body}`));
        } else {
          const accessToken = JSON.parse(body).access_token;
          resolve(accessToken);
        }
      });
    });
  }

  static isTokenExpired(accessToken) {
    const decoded = jwt.decode(accessToken);

    if (!decoded || !decoded.exp) {
      return true;
    }

    const expTimestamp = decoded.exp;
    //Convert expTimestamp to MS to ensure accurate comparison with Date.now(), which returns time in milliseconds.
    const expDateTimeOffset = new Date(expTimestamp * 1000);
    return Date.now() >= expDateTimeOffset;
  }

  static async fetchToken(currentToken, clientId, clientSecret, url) {
    if (currentToken && !TokenHelper.isTokenExpired(currentToken)) {
      return currentToken;
    } else {
      return await TokenHelper.generateTokenHttp(clientId, clientSecret, url);
    }
  }
}

module.exports = TokenHelper;

Last updated