0 votes
1 view
in Web Technology by (14.5k points)

Burned two hours of my life on this and wondering if fresh eyes can help.

I am attempting to contact auth0 to get access token for the management API.

The provide sample code, using request module, which works perfectly (I have replaced the key/secret values):

var request = require("request");

var options = { method: 'POST',

  url: 'https://dev-wedegpdh.auth0.com/oauth/token',

  headers: { 'content-type': 'application/json' },

  body: '{"client_id":"myID","client_secret":"mySecret","audience":"https://dev-wedegpdh.auth0.com/api/v2/","grant_type":"client_credentials"}' };

request(options, function (error, response, body) {

  if (error) throw new Error(error);

  res.json(JSON.parse(response.body).access_token)

});

I have my ID and Secret stored in .env file, so was able to adjust to this, which also works fine:

var options = { method: 'POST',

    url: 'https://dev-wedegpdh.auth0.com/oauth/token',

    headers: { 'content-type': 'application/json' },

    body: 

      JSON.stringify({

        grant_type: 'client_credentials',

        client_id: process.env.auth0AppKey,

        client_secret: process.env.auth0AppSecret,

        audience: 'https://dev-wedegpdh.auth0.com/api/v2/'})

  }

  request(options, function (error, response, body) {

    if (error) throw new Error(error)

    res.json(JSON.parse(response.body).access_token)

  })

I try to make the exact same request using axios and I receive 404 error:

let response = await axios.post(

  'https://dev-wedegpdh.auth0.com/api/v2/oauth/token', 

  JSON.stringify({

    grant_type: 'client_credentials',

    client_id: process.env.auth0AppKey,

    client_secret: process.env.auth0AppSecret,

    audience: 'https://dev-wedegpdh.auth0.com/api/v2/'

  }),

  { 

    headers: {'content-type': 'application/json'},

  }

)

I have tried several different formats or configurations for the post function. Anyone see what I am doing wrong???

1 Answer

0 votes
by (25.1k points)

In axios post body, you need to send data as JSON, no need to use JSON.stringify.

let response = await axios.post(

  "https://dev-wedegpdh.auth0.com/api/v2/oauth/token",

  {

    grant_type: "client_credentials",

    client_id: process.env.auth0AppKey,

    client_secret: process.env.auth0AppSecret,

    audience: "https://dev-wedegpdh.auth0.com/api/v2/"

  },

  {

    headers: { "content-type": "application/json" }

  }

);

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...