Last active
July 15, 2018 20:55
-
-
Save jamesbulpin/baac3062239a225acce5403febe515ae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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