Oauth2 request token from AWS Lambda - node.js

I am testing my AWS Lambda nodejs locally via SAM, and I need to make an Oauth2 request to a third party API which I also have running locally.
I am trying to do this:
request({
url: 'http://localhost:4040/auth/token',
method: 'POST',
auth: {
user: 'xxx',
pass: 'xxx'
},
form: {
'grant_type': 'client_credentials'
}
}, function(err, res) {
var json = JSON.parse(res.body);
console.log("Access Token:", json.access_token);
});
However, I am getting this info when invoking my function:
ERROR Uncaught Exception {"errorType":"TypeError","errorMessage":"Cannot read property 'body' of undefined","stack":["TypeError: Cannot read property 'body' of undefined","
I am not sure what I am doing wrong here? Any pointers?

Related

Firebase Auth REST API: OAuth sign-in with Twitter gives error 32 "could not authenticate you"

I'm writing a function in Node.js to log a user into Firebase using Twitter credentials, via the REST API (requests are made using the request library). I'm able to use the Twitter credentials to post a tweet, but attempting to sign in to Firebase with /accounts:signInWithIdp is returning the following error:
{ error:
{ code: 400,
message: 'INVALID_IDP_RESPONSE : Failed to fetch resource from https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true, http status: 401, http response: {"errors":[{"code":32,"message":"Could not authenticate you."}]}',
errors: [ [Object] ] } }
This is my code:
loginWithOAuth = (idToken, postBody, onCompletion, onError) => {
var form = {
postBody: querystring.stringify(postBody),
requestUri: 'request uri',
returnIdpCredential: 'false',
returnSecureToken: 'true',
}
request.post({
url: 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp?key=' + firebase_api_key,
body: form,
json: true
}, (error, r, body) => {
// ...
});
}
where postBody is of the form
{
access_token: 'token',
oauth_token_secret: 'token secret',
providerId: 'twitter.com'
}
My Twitter app has permission to access user emails. I've also whitelisted the requestUri in both Firebase and Twitter. Regenerating my app & user keys doesn't make a difference.
What am I missing?
postBody is not a stringified object, it is URL encoded:
var form = {
postBody: 'access_token=[TWITTER_ACCESS_TOKEN]&oauth_token_secret=[TWITTER_TOKEN_SECRET]&providerId=twitter.com',
requestUri: 'request uri',
returnIdpCredential: 'false',
returnSecureToken: 'true',
}

cypress retrieve JWToken and set as header for further requests

When trying to test a express webapplication i build the test should first authenticate to retrieve a JWT token, the token retrieving works but the method to set the header for further requests doesn't work.
This code creates the method to run when authentication is needed,
Cypress.Commands.add("userRequest", function(requestObj) {
// Make a login request, returning a JWT token
cy.request({
method: 'POST',
url: '/credentials',
body: {
"name": "test_user",
"password": "test123_"
}
}).then(function(response) {
requestObj.headers = requestObj.headers || {};
requestObj.headers.Authentication = response.body.token;
return cy.request(requestObj);
});
This is the code that runs
it('retrieves one user', function () {
cy.userRequest(cy.request({
url: '/users/1'
})).then(function (response) {
expect(response.body.name).to.equal("admin");
});
});
BUT when the test runs the console tells me
CypressError: cy.request() failed on:
http://localhost:3000/users/1
The response we received from your web server was:
401: Unauthorized
This was considered a failure because the status code was not '2xx' or '3xx'.
Can anyone help me?
thanks in advance!
As I said in my comment that cypress works on async programming, so try with in support/command.js
Cypress.Commands.add('userRequest', (email, password) => {
Cypress.log({
name: 'loginViaAuth0',
});
const options = {
method: 'POST',
url: '/credentials',
"body":'userName='+email+'&Password='+password+'
};
cy.request(options)
});
Then in your code
cy.userRequest(userName,password)
.its('body').then((response)=>{
// Do your stuffs
})

error returned in postman to get access token but works in console for NodeJS

I am trying to access the token using authorization code after passing the authentication, it works in my console for nodejs using request-promise module however it doesnt work on postman it says
{
"error": "invalid_grant",
"error_description": "invalid authorization code"
}
however it works in the console for nodeJS
{"access_token":"eyJhbGciOiJIUzI1NiJ9.7DkDzFz89Y-W-HLlwnqA0YmA_mMrR8nZV44eC1gAJjEp2Zmq8SE9q0UmzXuU-hHuXseMNvpqQeRMhHeVTbn8J_ZCQmkkAgZ359CnKvnXe3mZoYAWM4oQbtJFefoa7mwsAEFKScyEaIqi1DqHTItVqZfbCYdzrbee88E2-pWteiE.CHAvVIanJrUlTZZ25LMUTzW7IO4qRGZ_B_wN7c5Kfkk","token_type":"Bearer","refresh_token":"uDhPe4dRJkUYB1rC9VuV","expires_in":2592000,"scope":"openid profile","id_token":"eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2FjY2Vzcy5saW5lLm1lIiwic3ViIjoiVWU4NTUzNTBiNDIzYzI5ZjExYjIwZTgwZTJiZmE4MmQ1IiwiYXVkIjoiMTU1Njc5NDgxOCIsImV4cCI6MTUxNzkzMDc3MCwiaWF0IjoxNTE3OTI3MTcwLCJuYW1lIjoiSm9obiBCb3JqZSIsInBpY3R1cmUiOiJodHRwczovL3Byb2ZpbGUubGluZS1zY2RuLm5ldC8waG1URGV0bUpWTW50NUhCem5YUnhOTEVWWlBCWU9NalF6QVhJcVNBNGVQaDVSSzNRcFRINHVGQXdiUEI5V0pYTW9RWGgxR1Y5UGIwMVQifQ.mYUWJQ-YLrz4zEer5n1J-R3S1W37mDLx6g_mVmmWDTk"}
this is the code using nodeJS
var data = {
grant_type: "authorization_code",
code: qC,
redirect_uri: "https://sample.com/profile", //edited for security
client_id: 1, // edited for security
client_secret: "9" //edited for security
}
var options = {
method: 'POST',
url: 'https://api.line.me/oauth2/v2.1/token',
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
// payload: 'grant_type=authorization_code&code="'+queryCode+'"&redirect_uri=https://line-poc-demo.herokuapp.com/profile&client_id=1556794818&client_secret=98760fb0cea2aebdf7848ecf93c19cf4',
form: data
}
//
rp(options)
.then(function (parsedBody) {
// POST succeeded...
console.log('bick dig' + parsedBody);
})
.catch(function (err) {
// POST failed...
console.log('err ' + err);
});
Is there something wrong with my code? Thank you, any help will be appreciated.

OAuth2 using Curl/Node.js is not giving any response

I'm able to sucessfully create the Access token using postman with following parameters,
Callback URL: https://www.getpostman.com/oauth2/callback
Token Name:
Auth URL:
Access Token URL:
Client ID:
Client Secret:
Grant Type:Client Credentials.
But I could not able to get the access token via Curl or node.js as below,
var request = require("request");
var options = { method: 'POST',
url: '',
headers: { 'content-type': 'application/json' },
body: '{"client_id":"","client_secret":"","audience":","grant_type":"client_credentials"}' };
request(options, function (error, response, body) {
if (error) console.log(error);
//console.log(response);
console.log(body);
});
where I mapped my postman details to node.js script as,
Auth URL: url
Access Token URL: audience
Client Id: client_id
Client Secret: client_secret
Grant Type: grant_type
But I didn't any response. May I Know where i went wrong? or do we have any other mechanism to get the OAuth2 access token?
I'm just followed the script from https://manage.auth0.com/#/apis/590983763e3ae44a0dd1a219/test
After few research, I myself found the solution to generate the OAuth2 token through the code using the request, and I mapped by Postman values into the request_options as,
const options = {
url: access_token_url,
method: 'POST',
auth: {
user: client_id,
pass: client_secret,
},
form: {
grant_type: grant_type,
},
};
and used the request method to get the access token by,
request(options, (error, response, body) => {
if (error) return reject(error);
return resolve(body);
});
This helps me to generate the OAuth2 access token inside my script and fixed my requirement.

Unexpected token N in JSON at position 0

guys. I have a than error in my NodeJS rest API, and can't resolve this.
My idea is make a github login, this app working like this.
Href to github url returning a temporal code in callback.
Latter, send this temporal code to my REST API and with rest api make a fetch request to other endpoint of the github api, and this endpoint should return access_token=12345 (this access token is a example), for latter send this token to frontend, and convert the token in a JWT token and also send to frontend for latter storage in a localStorage to use it.
My code in NodeJS
router.post("/users/github/:code",function(req,res){
fetch('https://github.com/login/oauth/access_token/', {
method: 'GET',
client_id: 'xxxx',
client_secret: 'xxxx',
code: req.params.code,
accept: 'json',
})
.then(function(res) {
return res.json();
}).then(function(json) {
console.log(json);
});
});
PD: I use node-fetch module for this. https://www.npmjs.com/package/node-fetch
The solution
router.post("/users/github/:code",function(req,res){
fetch('https://github.com/login/oauth/access_token/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
client_id: 'xxxx',
client_secret: 'xxxx',
code: req.params.code
})
}).then(function(res) {
return res.json();
}).then(function(body) {
res.json(body);
});
});

Resources