Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST request to Graph API fails with Bad Request

I am developing a script to access the Graph API to read all users in our AD. I am performing a request with AXIOS via:

    let response;
    try {
        response = await axios.post(`https://login.microsoftonline.com/${config.get('azure.tenant')}/oauth2/v2.0/token`, {
            client_id: config.get('azure.appId'),
            scope: config.get('azure.scope'),
            client_secret: config.get('azure.secret'),
            grant_type: config.get('azure.grantType')
        });
    } catch (e) {
        res.send(e);
    }

This fails, though, with:

{
"message": "Request failed with status code 400",
"name": "Error",
"stack": "Error: Request failed with status code 400\n    at createError (C:\\_Apps\\repos\\timesAPI\\node_modules\\axios\\lib\\core\\createError.js:16:15)\n    at settle (C:\\_Apps\\repos\\timesAPI\\node_modules\\axios\\lib\\core\\settle.js:17:12)\n    at IncomingMessage.handleStreamEnd (C:\\_Apps\\repos\\timesAPI\\node_modules\\axios\\lib\\adapters\\http.js:237:11)\n    at IncomingMessage.emit (events.js:194:15)\n    at endReadableNT (_stream_readable.js:1103:12)\n    at process._tickCallback (internal/process/next_tick.js:63:19)",
"config": {
"url": "https://login.microsoftonline.com/86xxxxxxxxx8df7b/oauth2/v2.0/token",
"method": "post",
"data": "{\"client_id\":\"18xxxxxxxxf5x\",\"scope\":\"https://graph.microsoft.com/.default\",\"client_secret\":\"/xxxxxxxS:6xxxxxsxxQ\",\"grant_type\":\"client_credentials\"}",
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=utf-8",
"User-Agent": "axios/0.19.0",
"Content-Length": 184
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"m

axContentLength": -1
}
}

To do this, I am following the following tutorial: https://learn.microsoft.com/en-us/graph/auth-v2-service, which says, to access the api via:

// Line breaks are for legibility only.

POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token HTTP/1.1 Host: login.microsoftonline.com Content-Type: application/x-www-form-urlencoded

client_id=535fb089-9ff3-47b6-9bfb-4f1264799865 &scope=https%3A%2F%2Fgraph.microsoft.com%2F.default &client_secret=qWgdYAmab0YSkuL1qKv5bPX &grant_type=client_credentials

Am I just sending the headers wrong?

like image 881
rStorms Avatar asked Dec 05 '25 08:12

rStorms


1 Answers

Solved it. I sent the credentials using a string as the second argument: client_id=${config.get('azure.appId')}&scope=${config.get('azure.scope')}&client_secret=${config.get('azure.secret')}&grant_type=${config.get('azure.grantType')}

like image 172
rStorms Avatar answered Dec 06 '25 20:12

rStorms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!