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;
import jwt
import requests
from datetime import datetime
def generateTokenHttp(clientId, clientSecret, url='https://api.korewireless.com/Api/token'):
if clientId == "" and clientSecret == "":
raise Exception("Client Id,Secret Invalid")
data = "grant_type=client_credentials&client_id={clientId}&client_secret={clientSecret}".format(
clientId=clientId, clientSecret=clientSecret)
headers = {"content-type": "application/x-www-form-urlencoded",
"cachecontrol": "no-cache", }
response = requests.post(url=url, data=data, headers=headers)
if response.status_code >= 200 and response.status_code < 300:
return response.json()["access_token"]
else:
raise Exception("Error In Fetching Token"+response.text)
def isTokenExpired(access_token):
algorithm = jwt.get_unverified_header(access_token).get('alg')
decodedToken = jwt.decode(
jwt=access_token, verify=False, algorithms=algorithm, options={"verify_signature": False})
expTimestamp = decodedToken.get('exp')-300
# Token is invalid if it doesn't contain an expiration time
if not expTimestamp:
return True
expDatetime = datetime.utcfromtimestamp(expTimestamp)
nowDatetime = datetime.utcnow()
return nowDatetime >= expDatetime
def fetchToken(currentToken, clientId, clientSecret, url='https://api.korewireless.com/Api/token'):
if currentToken != "":
if isTokenExpired(currentToken):
return generateTokenHttp(clientId, clientSecret, url)
else:
return currentToken
else:
return generateTokenHttp(clientId, clientSecret, url)
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/dgrijalva/jwt-go"
)
func GenerateToken(clientId string, clientSecret string) (string, error) {
var token = ""
url := "https://api.korewireless.com/Api/token"
method := "POST"
if strings.TrimSpace(clientId) == "" || strings.TrimSpace(clientSecret) == "" {
return "", errors.New("client ID or Secret is invalid")
}
payload := strings.NewReader("grant_type=client_credentials&client_id=" + clientId + "&client_secret=" + clientSecret)
client := &http.Client{}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
return token, err
}
req.Header.Add("cache-control", "no-cache")
req.Header.Add("content-type", "application/x-www-form-urlencoded")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return token, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return token, err
}
var data map[string]interface{}
json.Unmarshal(body, &data)
fmt.Println(string(body))
if res.StatusCode != 200 {
return token, err
}
token = data["access_token"].(string)
return token, err
}
func IsTokenExpired(accessToken string) bool {
token, _, err := new(jwt.Parser).ParseUnverified(accessToken, jwt.MapClaims{})
if err != nil {
fmt.Println(err)
return true
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
fmt.Println(err)
return true
}
exp, ok := claims["exp"].(float64)
if !ok {
fmt.Println(err)
return true
}
// Convert the expiration time from seconds since epoch to a DateTime object. We use `time.Unix(int64(exp), 0)` to create a DateTime object from the exp value, We then compare this expiration time with the current time, minus 5 seconds to account for any potential clock skew and to ensure that we consider the token expired a few seconds before the actual expiration time to avoid any issues with very precise timing.
expTime := time.Unix(int64(exp), 0)
return time.Now().UTC().After(expTime.Add(-5 * time.Second))
}
func FetchToken(currentToken string, clientID string, clientSecret string) (string, error) {
if currentToken != "" {
if IsTokenExpired(currentToken) {
return GenerateToken(clientID, clientSecret)
} else {
return currentToken, nil
}
} else {
return GenerateToken(clientID, clientSecret)
}
}
using System.Text.Json;
using System.IdentityModel.Tokens.Jwt;
namespace Example
{
public static class TokenHelper
{
private static async Task<string> GenerateTokenHttp(string clientId, string clientSecret, string url)
{
if (string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(clientSecret))
{
throw new Exception("Client Id or Secret is invalid");
}
var data = $"grant_type=client_credentials&client_id={clientId}&client_secret={clientSecret}";
var content = new StringContent(data, System.Text.Encoding.UTF8, "application/x-www-form-urlencoded");
using var client = new HttpClient();
var response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
var responseString = await response.Content.ReadAsStringAsync();
var accessToken = JsonSerializer.Deserialize<AccessToken>(responseString).access_token;
return accessToken;
}
else
{
var error = await response.Content.ReadAsStringAsync();
Console.WriteLine ("CleintId:" + clientId );
throw new Exception($"Error in fetching token. {error}");
}
}
private static bool IsTokenExpired(string accessToken)
{
var handler = new JwtSecurityTokenHandler();
var token = handler.ReadJwtToken(accessToken);
if (!token.Payload.ContainsKey("exp"))
{
return true;
}
var exp = token.Payload["exp"];
if (exp is not long expTimestamp)
{
return true;
}
// Convert the expiration time from seconds since epoch to a DateTime object.
// We use`DateTimeOffset.FromUnixTimeSeconds(expTimestamp).UtcDateTime` to create a DateTime object from the exp value, then compare this expiration time with the current time to determine if the token has expired.
var expDateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(expTimestamp).UtcDateTime;
return DateTime.UtcNow >= expDateTimeOffset;
}
public static async Task<string> FetchToken(string currentToken, string clientId, string clientSecret, string url)
{
if (!string.IsNullOrWhiteSpace(currentToken))
{
if (IsTokenExpired(currentToken))
{
return await GenerateTokenHttp(clientId, clientSecret, url);
}
else
{
return currentToken;
}
}
else
{
return await GenerateTokenHttp(clientId, clientSecret, url);
}
}
}
public class AccessToken
{
public string access_token { get; set; }
}
}
Last updated