Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting access token with axios

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!

like image 238
Mike Avatar asked Jan 18 '17 12:01

Mike


People also ask

How do I get my access token?

After you have added an OAuth1 profile to the request, you need to configure it. This topic describes the settings and menus you use to configure OAuth 1.0 authorization. To use OAuth1 authorization in requests, you need to specify the Access Token and Token Secret (access token secret) values.


2 Answers

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.

like image 145
IzumiSy Avatar answered Sep 18 '22 00:09

IzumiSy


I have solved my problem with this code.

var reqData = "grant_type=password&username=test&password=asd";
         Axios({
    method: 'post',
    url: 'http://localhost:60439/token',
        data: (reqData),   

    headers: { 
      "Content-Type": "application/x-www-form-urlencoded",
    }
  }).then((response) =>{
            console.log(response)
        }).catch((error) =>{
            console.log(error);
        })
like image 30
DKR Avatar answered Sep 21 '22 00:09

DKR