0

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?

henser
  • 3,307
  • 2
  • 36
  • 47
  • 1
    Well your `"Content-Type": "application/json; charset=utf-8"` is wrong. You need to submit form-data. – juunas May 23 '19 at 09:52
  • I'd previously tried;- "Content-Type": "application/x-www-form-urlencoded" and then req.write("client_id=&scope=https%3A%2F%2Fgraph.microsoft.com&client_secret=&grant_type=client_credentials") but had no success with this either... – FoggyNotCloudy May 23 '19 at 10:11
  • Have you tried using MSAL.js? – juunas May 23 '19 at 10:15
  • According to the Microosft documentation MSAL.js doesn't support daemon apps [link](https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-daemon-app-configuration) – FoggyNotCloudy May 23 '19 at 14:37
  • Ahh.. That might be true :| – juunas May 23 '19 at 14:38

0 Answers0