Node JS & Auth0 | Get profile - node.js

Hey developer friends,
I'm building a small alexa skill & use auth0 as the authentication system. Now I want to get the userinfo/profile of the user, because I need the userId. In the request from alexa is an an accessToken. With that token, I want to be able to get the information from auth0.
var AuthenticationClient = require('auth0').AuthenticationClient;
var auth0 = new AuthenticationClient({
domain: '[MY NAME].eu.auth0.com',
clientId: '[MY CLIENT ID]',
clientSecret: '[MY CLIENT SECRET]'
});
Then in the actual function:
const access_token = session.user.accessToken;
console.log("ACCESSTOKEN:", access_token)
auth0.getProfile(access_token, function (err, userInfo) {
if(err) {
console.log("failed to retrieve profile", err)
} else {
const userId = JSON.parse(userInfo)['sub'];
console.log(userId);
}
}
When I run the code, I get the error 401 Unauthorized from auth0, although I use the provided accessToken. The accessToken is something like this in the amazon request: "VDMj7VBJ0EaJ1XZhvVRUfPgYNtxviro"
Any suggestions on how to do that properly?

I initalized the auth module twice, fixed it & now it works fine!

Related

Twitter oAuth using chrome extension

I am working on twitter oauth through chrome extension. I need to get oauth_token to authenticate the user. I am referring to https://developer.twitter.com/en/docs/tutorials/authenticating-with-twitter-api-for-enterprise/oauth1-0a-and-user-access-tokens. Can you guide me to send post request for my oauth token in javascript ?
You can refer to the above link for steps but I need to implement my post request in background.js instead to sending it in postman. I need my ext to create new request for each login, which for create different oauth token for each session.
I want to create a post request with following requirements:
URL-'https://api.twitter.com/oauth/request_token'
query- 'oauth_callback':'oob'
auth- we want to provide consumer key and consumer secret here
headers- 'Content-Type':'application/json'
This is a screenshot of postman. On implementing this, the post request returns oauth token and secret.
Please help me out on this.
import oauth from 'oauth';
const oauthCallback = process.env.FRONTEND_URL;
const CONSUMER_KEY = process.env.CONSUMER_KEY;
const CONSUMER_SECRET = process.env.CONSUMER_SECRET;
const _oauth = new oauth.OAuth(
'https://api.twitter.com/oauth/request_token',
'https://api.twitter.com/oauth/access_token',
CONSUMER_KEY, // consumer key
CONSUMER_SECRET, // consumer secret
'1.0',
oauthCallback,
'HMAC-SHA1',
);
export const getOAuthRequestToken = () => {
return new Promise((resolve, reject) => {
_oauth.getOAuthRequestToken((error, oauth_token, oauth_token_secret,
results) => {
if (error) {
reject(error);
} else {
console.log({ oauth_token, oauth_token_secret, results });
resolve({ oauth_token, oauth_token_secret, results });
}
});
});
};
Try this method in your backend to get the OAuth token and secret. It helped in my case, maybe it can work for you as well.
Use this to install oauth lib
npm i oauth
Refer for more info:
https://javascript.works-hub.com/learn/building-with-twitter-authentication-35ad6

How to verify Google signin (via Firebase) idToken in nodejs backend?

Trying to verify idToken of a user signed in via firebase authentication (Google signin) in nodejs server. Server throws Firebase ID token has invalid signature.
Tried verifying with firebase-admin as well as jsonwebtoken with public key from the url: https://www.googleapis.com/robot/v1/metadata/x509/securetoken#system.gserviceaccount.com. Both methods work perfect for users signed in with a password, but throws 'Invalid Signature' in case of a user signed in via google.
Is there anything I am doing wrong? Do I need to verify with google-auth-library instead?
Code:
import * as admin from "firebase-admin";
admin.initializeApp({
credential: admin.credential.cert(require("../../serviceAccount")), // file received from firebase project settings page
databaseURL: "as mentioned in the firebase project settings page",
});
// Some code here
var token = "token received from client side";
var decoded = await admin.auth().verifyIdToken(token);
PS:
All client side features (after signing in) are working fine.
Everything else on the backend is working fine.
Decoding the token in both cases gives expected JSON.
For test run, token is being forceRefreshed everytime before calling the API.
OP here,
I am dumb.
I was using the print() function of flutter to log the token and call the API myself. Didn't know Flutter's print function has an output character limit. Login using password gives smaller tokens thus the whole token was logged. But Google sign in gives a longer token, longer than the output character limit of print.
Solution : Use log function from 'dart:developer' package.
import 'dart:developer';
//
log(await _auth.idToken);
const { OAuth2Client } = require("google-auth-library");
const client = new OAuth2Client(googleClient[process.env.ENV])
let token = 123456789011-crhch2kuum79bk0qr3usa39f7b9chikc.apps.googleusercontent.com
async function googleLoginVerify(token) {
try {
const ticket = await client.verifyIdToken({
idToken: token,
audience: googleClient[process.env.ENV],
});
const payLoad = ticket.getPayload();
return {
success: true,
data: payLoad,
};
} catch (err) {
console.log(err.message);
return {
success: false,
message: err.message,
};
}
}

Can't get user google account gender and birthday fields with google People API. (Using OAuth2client)

I am implementing authentication with google in my mobile flutter app. I get the access_token in my app, and then I send it to backend which is written with Node.js. And thene I need to fetch user basic info + birthday and gender. In Google Cloud Platform console I did all configs, I added certain scopes,'https://www.googleapis.com/auth/user.birthday.read', 'https://www.googleapis.com/auth/user.gender.read',. I enabled Google People API. But I still can not get birthday and gender. Here is backend part from.
const token =
"HARDCODED_ACCESS_TOKEN";
var google = require("googleapis").google;
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2();
oauth2Client.setCredentials({
access_token: token,
scope: "https://www.googleapis.com/auth/user.gender.read",
});
var oauth2 = google.oauth2({
auth: oauth2Client,
version: "v2",
});
oauth2.userinfo.get(function (err, res) {
if (err) {
console.log(err);
} else {
console.log(res.data);
}
});
And here what I got in response.
I tried almost everything, but still couldn't get gender and birthday.
In order to get information about gender and birthdays from the authenticated user, you can call People API's people.get with resourceName=people/me and personFields=genders,birthdays:
oauth2Client.setCredentials({
access_token: token,
});
const service = google.people({version: 'v1', auth: oauth2Client});
service.people.get({
resourceName: 'people/me',
personFields: 'genders,birthdays'
}, (err, res) => {
// Do your thing
});
Notes:
You didn't provide the code for most of the authentication process, but please note that the scopes have to be provided before retrieving the access_token, since the access token depends on those scopes. Also, I'd suggest you to set a refresh_token, since the access_token will expire in an hour. For more information about the OAuth process, please take a look at the Node.js quickstart.
It is assumed that both genders and birthdays are added to the authenticated user's account.

How to use Google oAuth with Node.js backend and Angular frontend?

I am using Node.js on backend and creates a token for a user each time logins. angularx-social-login package makes it very easy to integrate Google OAuth with Angular but how to use it with API? After successful login the Google returns user information with token. I was thinking to send this information to backend and login the user but for that I need to create a route which accepts email address and logins user. And this will return JWT token which is not secure. By secure I mean, anyone can access the route without Google Authentication and generate token.
I am looking for ideas how developers achieved this.
I found google-auth-library client package for Node.js managed by Google.
Here is the follow:
Login user with Angular
Send the idToken to backend
Validate token and response to Angular
Node.js:
exports.googleLogin = function(req, res, next) {
//verify the token using google client
return googleClient
.verifyIdToken({
idToken: req.body.token,
audience: config.google.clientID
})
.then(login => {
//if verification is ok, google returns a jwt
var payload = login.getPayload();
var userid = payload['sub'];
//check if the jwt is issued for our client
var audience = payload.aud;
if (audience !== config.google.clientID) {
throw new Error(
'error while authenticating google user: audience mismatch: wanted [' +
config.google.clientID +
'] but was [' +
audience +
']'
);
}
//promise the creation of a user
return {
name: payload['name'], //profile name
pic: payload['picture'], //profile pic
id: payload['sub'], //google id
email_verified: payload['email_verified'],
email: payload['email']
};
})
.then(user => {
return res.status(200).json(user);
})
.catch(err => {
//throw an error if something gos wrong
throw new Error(
'error while authenticating google user: ' + JSON.stringify(err)
);
});
};

Node.js OAuth2: Get Google+ activities

From today I'm not able to retrieve my Google+ activities by placing a GET request to this url:
https://www.googleapis.com/plus/v1/people/me/activities/public?key={API_KEY}
I'm getting a 401 error. So I tried to sign the request using the node.js oauth2 library, including a pre-generated user token, but I'm getting the same error. The js code for my test script is:
var OAuth2 = require('oauth').OAuth2,
GOOGLEPLUS_APP_ID = {APP_ID},
GOOGLEPLUS_APP_SECRET = {APP_SECRET},
accessToken = {USER_TOKEN};
var _oauth2 = new OAuth2(GOOGLEPLUS_APP_ID, GOOGLEPLUS_APP_SECRET, '',
'https://accounts.google.com/o/oauth2/auth',
'https://accounts.google.com/o/oauth2/token');
_oauth2.get('https://www.googleapis.com/plus/v1/people/me/activities/public?key={API_KEY}',
accessToken, function (err, body, res) {
if (err) {
console.log('error:');
console.log(err);
}
else console.log(body);
});
I placed the same request to get the basic user info (url: https://www.googleapis.com/oauth2/v1/userinfo) and works OK.
Can you please assist me with this?
Thank you.
If you have the access token already you should be able to use {?|&}access_token=X to get the result, example below.
var accessToken = 'XYZ';
require('http').get('https://www.googleapis.com/plus/v1/people/me/activities/public?access_token=' + accessToken, function(result){
//Use result here!
});
More information can be found within the Google+ API (Common Parameters) section

Resources