Fetching a test token using axios

So I have this working using the following with requests:

	async getToken() {
		var body={
			"client_id":clientId,
			"client_secret":clientSecret,
			"audience":"https://staging-site.auth0.com/api/v2/",
			"grant_type":"client_credentials"
			};		
		const grab=request.post({
			"headers":{
				"content-type": "application/json"
				},
				"url" : `${baseAuth0ApiUrl}/oauth/token`,
				"json":body
			});
		let token=await grab;
	};

This worked fine, however as part of a recent refactor I have been asked to phase out requests in favor of axios. Unfortunately I can’t seem to get the equivalent request to work:

async** getToken() {
   let data={
         "client_id":clientId,
         "client_secret":clientSecret,
         "audience":"https://staging-site.auth0.com/api/v2/",
         "grant_type":"client_credentials"
         };

   let headers={
        "content-type": "application/json"
        };
   let url = `${baseAuth0ApiUrl}/oauth/token`;
   try {
        const token = axios.post(url, {"headers":headers,"data":data});
        let tokenParsed= await token;
        return `${tokenParsed.data.token_type} ${tokenParsed.data.access_token}`; 
        }
   catch (error){
      console.error(error);
      console.log("Token request failed!");
      return false ;
   }
}

I get a data: { error: 'access_denied', error_description: 'Unauthorized' } from the axios call, can anyone tell me what it is I am doing wrong?

Since you want to get an access token for the Auth0 Management API, you might just want to make your life easier and just use the ManagementClient :slight_smile:

const ManagementClient = require("auth0").ManagementClient;

See code examples on:

(Not an Axios/Node expert, I’d otherwise compare both requests (headers, params), see what’s missing.)

turns out all I had to do is reduce the axios call to:
const token = axios.post(url, data);

2 Likes

Perfect! Glad to hear that!

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.