Getting access token with axios - javascript

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:
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!

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.

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);
})

The Best solution was source using the following way. The client sends a POST request with following body parameters to the authorization server
grant_type with the value client_credentials
client_id with the the client’s ID
client_secret with the client’s secret
scope with a space-delimited list of requested scope permissions.
axios.post('https://exmaple.com/oauth/token',
'grant_type=client_credentials&scope=all&client_id=1&client_secret=bb'
)
.then(function(res) {
console.log(res);
})
.catch(error => {
console.log(error)
})

const axios = require("axios");
const qs = require("qs");
const url = "URL";
const data = {
grant_type: "client_credentials",
};
const auth = {
username: "Client ID",
password: "Client Secret",
};
const options = {
method: "post",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
data: qs.stringify(data),
auth: auth,
url,
};
axios(options)
.then((response) => {
console.log(response.data.access_token);
})
.catch((err) => {
console.log(err);
});

The following works. I got it by reading the above comments. The trick was the data field. To be clear use - data: "grant_type=client_credentials"
Example:
const axios = require("axios");
axios.request({
headers:{'Content-Type': 'application/x-www-form-urlencoded'},
url: "/oauth2/token",
method: "post",
baseURL: "https://<ServerFQDN>/",
data: "grant_type=client_credentials",
auth: {
username: "<username>",
password: "<password>"
}
});

Related

How to feed the payload data with Post request inside the Node api?

I call another api in NodeJS express api with request payload using certificate with Post request type but the payload is not accepting. The problem is, how to feed the payload data with Post request inside the Node api?
Just pass the payload with comma separated URL,
Example :
await axios.post('http://localhost:4000/createUser',
data
);
where data will be payload for another API
Here is an example with Axios
const axios = require('axios');
var dataToPost = {
email: "your email",
password: "your password"
};
let axiosConfiguration = {
headers: {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
}
};
axios.post('endpoint or url', dataToPost, axiosConfiguration)
.then((res) => {
console.log("Response: ", res);
})
.catch((err) => {
console.log("error: ", err);
})

Emulate Python HTTP request using JS Fetch

I can successfully do a simple HTTP request using python requests:
def renew_token():
"""
Send a request to renew the login token
"""
url = url
fields = {
"username": "username",
"password": "password"
}
r = requests.post(url, data=fields)
print(r)
I am trying to do the exact same request using javascript fetch, but with no luck.
async function renewToken(url = '', fields = {}) {
const response = await fetch(url, {
method: 'POST'
data: JSON.stringify(fields),
mode: 'cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json',
//'Content-Type': 'application/x-www-form-urlencoded',
},
});
return await response.json();
}
renewToken('url', { username: 'username', password: 'password' })
.then((data) => {
console.log(data); // JSON data parsed by `response.json()` call
});
The error I get back is :
{ data: null,
message: 'No username or password provided',
status: 'api-error' }
which implies there is something wrong with the content type. I've tried changing the content-type to 'application/x-www-form-urlencoded', but I get the same error.
What am I missing to emulate the python request using fetch?
Had to use form data , not sent data in body:
async function renewToken(url = '', fields = {}) {
const response = await fetch(url, {
method: 'POST', //
body: 'username=username&password=password',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
return await response.json();
}

How to logout the authenticated token correctly after API call returns response?

I have the below code on client side, on click event It sends a request server side node to get a token, then when token is returned from external url response. It passes that token onto the second ajax call to call a specific api route.
This all works great, but I want to logout the token after I get the response from a specific api route (using the token). So that after the response I don't have the token staying alive.
What would be a good way to accomplish this? My current solution is when the response for the specific api route is given, send a fetch request to /tokenrequest/logout to logout the token. But not sure if that is a correct or good way to do it.
getdata.addEventListener("click", function(e) { //simple button click to initiate api
e.preventDefault();
$.ajax({
method: "GET",
url: "/jdeapi",
error: function(request, status, error) {
console.log(error);
}
}).then(function(data) {
console.log(JSON.parse(data));
let rawData = JSON.parse(data);
var token = rawData.userInfo.token;
$.ajax({
method: "POST",
url: "/sendtojde",
data: {
token
}
}).then(function(data) {
console.log(data);
})
})
})
The node server side code is as follows for the token request
router.get('/jdeapi', function(req, res) {
let url = 'https://Aisserver:port/jderest/tokenrequest';
let data = {
username: 'username',
password: 'password',
deviceName: 'riolivApp'
}
fetch(url, {
credential: 'include',
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(response => response.text())
.then(text => res.json(text));
})
Then after the 2nd ajax call on client side, the server side call to fetch a specific api is as follows
router.post('/sendtojde', function(req, res) {
console.log(req.body.token);
let url = "https://Aisserver:port/jderest/poservice"
let data = {
token: req.body.token,
deviceName: 'riolivApp',
applicationName: "P4310",
version: "RMI0001"
}
fetch(url, {
credential: 'include',
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(response => response.text())
.then(text =>
res.json(text));
})

Axios Post Method to implement customized headers and with token value

I'm trying to write a Post method with Axios in NodeJS.
I have following things to pass as param in post method
url = http:/xyz/oauthToken
header 'authorization: Basic kdbvkjhdkhdskhjkjkv='\
header 'cache-control:no-cache'
header 'content-type: application/x-www-form-urlencoded'
data 'grant_type=password&username=user123&password=password123'
As I tried with following code but new to Axioz not sure how can exactly implement the header with grant type of body response.
var config = {
headers: {'Authorization': "bearer " + token}
};
var bodyParameters = {
data 'grant_type=password&username=user123&password=password123'
}
Axios.post(
'http:/xyz/oauthToken',
bodyParameters,
config
).then((response) => {
console.log(response)
}).catch((error) => {
console.log(error)
});
Any help/suggestion would be appreciated :-)
Currently, axios does not make it convenient to use form-encoded data; it's mostly optimized toward JSON. It's possible, though, as documented here.
const querystring = require('querystring');
const body = querystring.stringify({
grant_type: 'password',
username: 'user123',
password: 'password123'
});
axios.post('http:/xyz/oauthToken', body, {
headers: {
authorization: `bearer ${token}`,
'content-type': 'application/x-www-form-urlencoded'
}
});

ReactJS- Pass the JWT token as Authorization in axios method for http request

I have an application where we are generating a JWT token and passing that token in Header in the next api call.As a response of that, I should get a key.I am able to see the response through postman.I am using ReactJS in Front End and trying to achieve the same by passing the JWT token in Header while doing the api call but facing some issues.
My code-
getKey() {
let postData = {
vin: "5678",
id: "abc12",
};
axios({
method: "post",
url: "http://localhost:8080/generateKey",
headers: {
"Content-Type": "application/json"
},
data: postData
})
.then(function(response) {
setKey(response.data.key);
})
.catch(function(error) {
console.log(error);
getKeyError();
});
}
memberAuth() {
var self = this;
axios({
method: "GET",
url: "http://localhost:8080/authenticateMember",
headers: {
"Content-Type": "application/json",
"Authorization": localStorage.setItem()
},
data: {
"id":"xyzzy",
"password":"abc"
}
})
.then(function(response) {
//to do
}
I am trying to save the generated token (valid for 30mins) in a localStorage/SessionStorage but not sure if this is the right way. Can someone tell me where am I going wrong.
Create instance of your axios,
const agent = axios.create({
baseURL: config.api_url,
transformRequest: [transformRequest],
transformResponse: [transformResponse],
headers: { 'Content-Type': 'application/vnd.api+json' },
});
And then call this function to set headers dynamically
agent.defaults.headers.common['Authorization'] = `JWT ${localStorage.getItem('token')}`;
Then call methods of your axios instance to make API calls
agent.get(`${endpoint}search`, { params }),
agent.post(`${endpoint}search`, JSON.stringify(body)),

Categories

Resources