Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the node google client api to get user profile with already fetched token?

Getting a user profile info through curl

curl -i https://www.googleapis.com/userinfo/v2/me -H "Authorization: Bearer a-google-account-access-token"

Getting a user profile info through node https get request

const https = require('https');

function getUserData(accessToken) {
    var options = {        
                    hostname: 'www.googleapis.com',
                    port: 443,
                    path: '/userinfo/v2/me',
                    method: 'GET',
                    json: true,
                    headers:{
                        Authorization: 'Bearer ' + accessToken            
                   }
            };
    console.log(options);
    var getReq = https.request(options, function(res) {
        console.log("\nstatus code: ", res.statusCode);
        res.on('data', function(response) {
            try {
                var resObj = JSON.parse(response);
                console.log("response: ", resObj);
            } catch (err) {
                console.log(err);
            }
        });
    });

    getReq.end();
    getReq.on('error', function(err) {
        console.log(err);
    }); 

}

var token = "a-google-account-access-token";
getUserData(token)

How can I use this google node api client library to get the user profile info provided that I already have the access token? I can use the code above to get the profile but I thought it's probably better off to use the google api library to do it, but I can't figure out how to do that using this node google api client library.

A temporary access token can be acquired through playing this playground

like image 809
s-hunter Avatar asked Oct 16 '17 23:10

s-hunter


1 Answers

2021 Solution

This answer may divert from the originally asked question but I think it will be useful for some people who are getting google user information in the backend by generating AuthUrl and sending it to the client side and then receiving the data response in the call back URL after the user gives permission from the client side.

Some global declarations

import { google } from "googleapis";
const Oauth2Client = new google.auth.OAuth2(
  googleCredentials.CLIENT_ID,
  googleCredentials.CLIENT_SECRET,
  googleCredentials.REDIRECT_URI
);

Generate the Auth URL with the scopes

const SCOPE = [
  'https://www.googleapis.com/auth/userinfo.profile', // get user info
  'https://www.googleapis.com/auth/userinfo.email',   // get user email ID and if its verified or not
];
const auth_url = Oauth2Client.generateAuthUrl({
  access_type: "offline",
  scope: SCOPE,
  prompt: "consent",
  state: "GOOGLE_LOGIN",
});
return res.json({ url: auth_url });    // send the Auth URL to the front end

Get the user data in the callback

let code = req.query.code;    // get the code from req, need to get access_token for the user 
let { tokens } = await Oauth2Client.getToken(code);    // get tokens
let oauth2Client = new google.auth.OAuth2();    // create new auth client
oauth2Client.setCredentials({access_token: tokens.access_token});    // use the new auth client with the access_token
let oauth2 = google.oauth2({
  auth: oauth2Client,
  version: 'v2'
});
let { data } = await oauth2.userinfo.get();    // get user info
console.log(data);

Feel free to discuss in the comments if there's any confusion or error

like image 177
wingman__7 Avatar answered Oct 10 '22 04:10

wingman__7