Azure AD publisher’s authorization token request returned 302

In an Azure Function as a backend for my webpage, I requested an Azure AD publisher’s authorization token as per this page instructed. This is the line of codes of my Azure Functions:

  // Stringfy request body
  const postData = querystring.stringify({
    'grant_type': 'client_credentials',
    'client_id': client_id,
    'client_secret': client_secret,
    'resource': resource,
  });

  
  // Initiate options
  var httpAgent = new http.Agent();
  httpAgent.maxSockets = 200;
  const options = {
    hostname: 'login.microsoftonline.com',
    path: `/${tenantId}/oauth2/token`,
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    agent: httpAgent,
  }


  const tokenReq = http.request(options, (res) => {
    console.log(`STATUS: ${res.statusCode}`);
    console.log(`HEADERS: ${JSON.stringify(res.headers)}`);

    res.setEncoding('utf-8')

    res.on('data', (chunk) => {
      console.log(chunk);
      body += chunk;
    });

    res.on('end', () => {
      console.log('No more data in response.');
      console.log("body:" + body);
      context.res = {
        status: 200,
        body: body,
      };
    });
  });

  tokenReq.on('error', (e) => {
    console.log(`problem with request: ${e.message}`);
    context.res = {
      status: 500,
      body: `problem with request: ${e.message}`,
    }
  });


  // write data to request body
  tokenReq.write(postData);
  tokenReq.end();

The expected response was the access token that I require, however running it locally I got STATUS 302, and a header containing a location and some other parameters, as a response. In my understanding STATUS 302 states that the URL is moved temporarily to the location provided in the header. Now, I don’t know what I’m supposed to do, the request that I have to make is supposed to be a POST request so a redirection would not work. I’ve also tried to make a new request after receiving the redirect URL, but I got an error message saying: getaddrinfo ENOTFOUND {redirect URL from header}. What did I do wrong here?

Answer

The 302 error was caused by http module, you use require('http'); and http.request(options, (res).... to do the request, so it shows 302 error.

I suggest you to use var request = require('request'); to do the request, below is my function code for your reference (before use request module, you need to run npm install request to install it first):

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    var result = await generatetoken(context);
    context.res = {
        body: result
    };
}

function generatetoken(context){
    var request = require('request');

    var options = {
            'method': 'POST',
            'url': 'https://login.microsoftonline.com/<your tenant id>/oauth2/token',
            'headers': {
            'Content-Type': 'application/x-www-url-form-urlencoded'
        },
        form: {
        'client_id': 'xxxxxx',
        'grant_type': 'client_credentials',
        'resource': 'xxxxx',
        'client_secret': 'xxxxx'
        }
    };

    return new Promise(function(resolve, reject) {
        request(options, function(err, res) {
            if (err) {
                reject(err);
            } else {
                context.log(res.body);
                resolve(res.body);
            }
        })
    })
}

Leave a Reply

Your email address will not be published. Required fields are marked *