Skip to content

Instantly share code, notes, and snippets.

@jamesbulpin
Last active July 15, 2018 20:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesbulpin/baac3062239a225acce5403febe515ae to your computer and use it in GitHub Desktop.
Save jamesbulpin/baac3062239a225acce5403febe515ae to your computer and use it in GitHub Desktop.
var azureCognitiveServicesAuthEndpoint = 'https://northeurope.api.cognitive.microsoft.com/sts/v1.0/issueToken';
var azureCognitiveServicesSubscriptionKey = "[...]";
[...]
// Azure Cognitive Services interface
var _cachedAzureToken = null;
var _cachedAzureTokenExpires = null;
function azureGetAuthToken(callback) {
if (_cachedAzureToken && _cachedAzureTokenExpires) {
if ((new Date).getTime() < _cachedAzureTokenExpires) {
console.log("Using cached auth token: " + _cachedAzureToken);
callback(null, _cachedAzureToken);
return;
}
}
request({
url: azureCognitiveServicesAuthEndpoint,
method: "POST",
headers: {
'Content-Type' : 'application/x-www-form-urlencoded',
'Content-Length': 0,
'Ocp-Apim-Subscription-Key': azureCognitiveServicesSubscriptionKey
}
}, function (error, response, body){
if (error) {
callback(error, null);
}
else if (response.statusCode != 200) {
callback(body, null);
}
else {
_cachedAzureToken = body;
_cachedAzureTokenExpires = (new Date).getTime() + (9 * 60 * 1000); // Expires in 10 minutes, refresh in 9
console.log("Got auth token: " + _cachedAzureToken);
callback(null, _cachedAzureToken);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment