Search code examples
apigoogle-apps-scriptoauth-2.0office365access-token

Unable to generate OAuth 2.0 Access Token from Office365 via JavaScript


I'm trying to pull an access token from Office365's /token identity platform endpoint via OAuth 2.0 client credentials grant flow. I have my app registered, the client ID & secret, etc...

I can make the POST request in Postman and receive the access token without issue: enter image description here

However, when I try the POST request via JavaScript (by way of Google Apps Script), I receive an error message: AADSTS900144: The request body must contain the following parameter: 'grant_type'

I've already Google'd this error and found a bunch of different solutions, and have tried implementing them to no avail. I imagine this has to do with the URL encoding, but cannot figure it out.

Code:

function getO365() {
  // POST Request (To get Access Token)
  var tenantID = 'longstringhere'
  var appID = 'longstringhere'
  var appSecret = 'longstringhere'
  var graphScore = 'https://graph.microsoft.com/.default'

  var url = 'https://login.microsoftonline.com/' + tenantID + '/oauth2/v2.0/token'

  var data = {
    'client_id': appID,
    'scope': graphScore,
    'client_secret': appSecret,
    'grant_type': 'client_credentials'
  };

  var postOptions = {
    'method': 'POST',
    'headers': {
      'Accept': 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    'body': data,
    'redirect': 'follow'
  };

  var authToken = UrlFetchApp.fetch(url, postOptions);

}

The only real difference between my code and the JavaScript Fetch code I pulled off of Postman is:

var urlencoded = new URLSearchParams();
urlencoded.append("client_id", "longstringhere");
urlencoded.append("scope", "https://graph.microsoft.com/.default");
urlencoded.append("client_secret", "longstringhere");
urlencoded.append("grant_type", "client_credentials");

When I try to use URLSearchParams in Google Apps Script, I keep getting this error: ReferenceError: URLSearchParams is not defined

Any ideas? Thanks in advance!


Solution

  • This was resolved by changing 'body' to 'payload' for UrlFetchApp per the documentation. Edited code to reflect the change. Credit to @TheMaster for pointing out my mistake.

    'payload': data,//from   'body': data,