I have an Azure Timer Triggered Function that needs to make various calls to the Graph API, which means I need an OAuth2 Bearer token issued by my tenancy's AAD.
So I've written the function below, which based on code I've previously written to make Ajax calls, which makes a call to AAD to get the Bearer token I need.
I've tested the URL, Client ID, Client Secret, and Grant Type settings using Postman and they returned a valid Bearer Token for me to use. However the code makes the call, and nothing is returned, it just seems to hang. When test-run in the Azure portal I get a
Status 503 Service Unavailable.
async function getToken() {
return new Promise((resolve, reject) => {
try {
let https = require("https");
let url =
"https://login.microsoftonline.com/<azure_tenancy>.onmicrosoft.com/oauth2/token";
let options = {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "no-cache"
}
};
let body = {
grant_type: "client_credentials",
client_id: "<client_id>",
client_secret: "client_secret>",
resource: "https://graph.microsoft.com"
};
var req = https
.request(url, options, res => {
let data = "";
res.on("data", chunk => {
data += chunk;
});
res.on("end", () => {
resolve(JSON.parse(data));
});
})
.on("error", err => {
throw new Exception(e.message);
});
req.write(JSON.stringify(body));
req.end();
} catch (e) {
context.log("error caught");
reject(e);
}
});
}
Postman returns:
{
"token_type": "Bearer",
"expires_in": "3600",
"ext_expires_in": "3600",
"expires_on": "1558542984",
"not_before": "1558539084",
"resource": "https://graph.microsoft.com",
"access_token": "eyJ...e8mw"
}
So I know the URL, ID, and Secret I'm passing are correct. It must be something else in the code but I'm baffled as to what. Any clues?