I am trying to get a graph token from Azure AD with a post request having form data through Axios. The response throws an error Request failed with status code 404. The below is the code,
const axios = require('axios')
const FormData = require('form-data')
const bodyFormData = new FormData()
bodyFormData.append('client_id', <client id>)
bodyFormData.append('client_secret', <secret>)
bodyFormData.append('scope', <scope>)
bodyFormData.append('requested_token_use', <token use>)
bodyFormData.append('assertion', <token>)
axios
.post('https://login.microsoftonline.com/<tenantId>/oauth2/v2.0/token', bodyFormData, {
headers: bodyFormData.getHeaders(),
})
.then((response) => {
console.log('AXIOS RESPONSE ', response)
})
.catch((err) => {
console.log('AXIOS ERROR ', err)
})
The post request works fine in the postman. The response in Axios is also as expected if bodyFormData is removed from Axios request. When bodyFormData is added to the request I encounter an error.
AXIOS ERROR Error: Request failed with status code 404
Instead of using form-data use querystring
const axios = require('axios')
const querystring = require('querystring');
const data = querystring.stringify({
client_id: '<client id>',
client_secret: '<secret>',
scope: '<scope>',
requested_token_use: '<token use>',
assertion: '<token>'
});
axios.post('https://login.microsoftonline.com/<tenantId>/oauth2/v2.0/token', data)
.then((response) => {
console.log('AXIOS RESPONSE ', response)
})
.catch((err) => {
console.log('AXIOS ERROR ', err)
});
Try removing the headers part, it should work.
There should not be any reason having to get the headers from the FormData object, as it’s an API and will use other forms of authentication and could mess up the call.
It’s not a data scraping call that might be blocked by some security measure.