Dshiz
Dshiz

Reputation: 3331

How to convert Active Directory Token curl command to a node-fetch

CURL command that works successfully when I put my own Tenant ID, Client ID, and Client Secret in:

# Replace {tenant} with your tenant!
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'client_id=535fb089-9ff3-47b6-9bfb-4f1264799865&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret=qWgdYAmab0YSkuL1qKv5bPX&grant_type=client_credentials' 'https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token'

My attempt using node-fetch that errors out:

const fetch = require('node-fetch');
let  tenantId='<my tenant id>';

    let token = fetch(`https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`, {
        method: 'post',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            client_id: '<my client id>',
            scope: 'https://graph.microsoft.com',
            client_secret: '<my client secret>',
            grant_type: 'client_credentials',
        })
      }).then(function(response) {
        return response.json()
      }).then(json => {
          console.log(json)
      })

Error I'm receiving:

  error: 'invalid_request',
  error_description: "AADSTS900144: The request body must contain the following parameter: 'grant_type'.\r\n" +
    'Trace ID: <trace id>\r\n' +
    'Correlation ID: <correlation id>\r\n' +
    'Timestamp: 2021-05-12 22:27:30Z',
  error_codes: [ 900144 ],
  timestamp: '2021-05-12 22:27:30Z',
  trace_id: '<trace id>',
  correlation_id: '<correlation id>',
  error_uri: 'https://login.microsoftonline.com/error?code=900144'

What is wrong with the body in my node-fetch POST request?

By the way, I've tried with Axios and am getting the same result, too.

Upvotes: 2

Views: 509

Answers (1)

Vova Bilyachat
Vova Bilyachat

Reputation: 19484

AD is expecting form request, try this

const fetch = require('node-fetch');
let  tenantId='<my tenant id>';

    let token = fetch(`https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`, {
        method: 'post',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'client_id=<my client id>&scope=https://graph.microsoft.com&client_secret=<my client secret>&grant_type=client_credentials'
        }
      }).then(function(response) {
        return response.json()
      }).then(json => {
          console.log(json)
      })

Upvotes: 2

Related Questions