Getting access token with axios

Mike picture Mike · Jan 18, 2017 · Viewed 35.4k times · Source

I'm working with the Lyft API, and trying to figure out how to get an access token with axios with a node script.

I can manually get an access token by using Postman by filling out the form like this:

Getting token inside of Postman

When I fill out the form, I can get a new token from Lyft successfully.

I'm trying to translate this into a POST request using axios by doing this:

var axios = require('axios');
var data = {
"grant_type": "client_credentials",
"scope": "public",
"client_id": "XXXXXXXXX",
"client_secret": "XXXXXXXX"
};
var url = "https://api.lyft.com/oauth/token";
  return axios.post(url, data)
    .then(function(response){
        console.log(response.data)
    })
    .catch(function (error) {
      console.log(error);
    });

When I run the script, I get this error:

{ error_description: 'Unauthorized', error: 'invalid_client' }

What am I missing from my axios request? Any help would be appreciated!

Answer

IzumiSy picture IzumiSy · Jan 18, 2017

According to the docs from Lyft (https://developer.lyft.com/docs/authentication), you need to use HTTP Basic auth.

var axios = require("axios");

axios.request({
  url: "/oauth/token",
  method: "post",
  baseURL: "https://api.lyft.com/",
  auth: {
    username: "vaf7vX0LpsL5",
    password: "pVEosNa5TuK2x7UBG_ZlONonDsgJc3L1"
  },
  data: {
    "grant_type": "client_credentials",
    "scope": "public"    
  }
}).then(function(res) {
  console.log(res);  
});

Happy coding :)

!IMPORTANT THING!
I strongly recommend you to change your secret_id and client_secret asap, because they are not the things to be public, if you use them for an important project or something like that.