12

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

4 Answers 4

44

You can retrieve the user profile using the google node API client library. In this case, please retrieve the access token and refresh token as the scope of https://www.googleapis.com/auth/userinfo.profile. The sample script is as follows. When you use this sample, please set your ACCESS TOKEN.

Sample script :

var google = require('googleapis').google;
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2();
oauth2Client.setCredentials({access_token: 'ACCESS TOKEN HERE'});
var oauth2 = google.oauth2({
  auth: oauth2Client,
  version: 'v2'
});
oauth2.userinfo.get(
  function(err, res) {
    if (err) {
       console.log(err);
    } else {
       console.log(res);
    }
});

Result :

{
  id: '#####',
  name: '#####',
  given_name: '#####',
  family_name: '#####',
  link: '#####',
  picture: '#####',
  gender: '#####',
  locale: '#####'
}

If I misunderstand your question, I'm sorry.

17
  • yes, you misunderstood my question. The situation is that I already have the AccessToken, I don't want to and no need to use the api's oauth2 to retrieve the AccessToken. I am looking for how to use this api if I already have the AccessToken.
    – s-hunter
    Oct 17, 2017 at 0:29
  • @s-hunter I'm sorry for the inconvenience. I updated my answer. Please confirm it. The updated script can be used by your access token. And at this script, the access token is not retrieved.
    – Tanaike
    Oct 17, 2017 at 0:41
  • 1
    Confirmed and accepted your answer. Would you share how did you come to this solution? I can't seem to find any documentation or sample code from that repo for these two methods, oauth2Client.setCredentials and oauth2.userinfo.get. Did you back trace the source code?
    – s-hunter
    Oct 17, 2017 at 1:05
  • 2
    @s-hunter I always get the information from README.md and the source of each client library for using Google APIs. About setCredentials, I get it from the document. From this information, I could get how to use oauth2Client. Then, about oauth2.userinfo.get for Node.js, I checked this. I think that there is more effective ways. But in this case, I did above. If this was not useful, I'm sorry.
    – Tanaike
    Oct 17, 2017 at 1:22
  • @s-hunter hey. i need to do same but i don't know why not working for me. i have added package googleapis . my script stopped in second line. any other package needed or its works only on googleapis?
    – dev dev
    Mar 29, 2018 at 6:29
11

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

3
  • 1
    Amazing it worked. Can you please share where did you get the relevant documentation because i am not able to find doc about google api on google, ironic.
    – Deiknymi
    May 11, 2021 at 19:28
  • 1
    Hi @Deiknymi ! I'm sorry I don't remember the documentation its been a long time, you can search for official docs on the internet or refer to a youtube video or blogs.
    – wingman__7
    May 13, 2021 at 13:10
  • 1
    well looks like the path of suffering is the the true path.
    – Deiknymi
    May 14, 2021 at 5:32
4

You can also decode the id_token that's in the response from oAuth2Client.getToken().

Remember that you need to have necessary scopes enabled for your app for the response to have this id_token. For an example, let's say we just need the user's email. So we'll use,

https://www.googleapis.com/auth/userinfo.email

To decode the token,

const response = await oAuth2Client.getToken(code);
const userInfo = JSON.parse(Buffer.from(response.tokens.id_token.split('.')[1], 'base64').toString());

console.log(userInfo);

This will output,

{
  "iss": "https://accounts.google.com",
  "azp": "1234987819200.apps.googleusercontent.com",
  "aud": "1234987819200.apps.googleusercontent.com",
  "sub": "10769150350006150715113082367",
  "at_hash": "HK6E_P6Dh8Y93mRNtsDB1Q",
  "hd": "example.com",
  "email": "[email protected]",
  "email_verified": "true",
  "iat": 1353601026,
  "exp": 1353604926,
  "nonce": "0394852-3190485-2490358"
}

This token simply is a JWT object which can be decoded eaisily. You can check this documentation and see even Google recommends this. The advantage of this method is that you don't have to make an extra request to Google APIs to get user's info.

0

Based on this anser: https://stackoverflow.com/a/46780714/140164

Here is another shorter way to achieve the same results.

const { google } = require('googleapis');
const oauth2Client = new google.auth.OAuth2()
const tokenInfo = await oauth2Client.getTokenInfo(*YourAccessToken*);
console.log(tokenInfo);
1
  • it will provide only info inside token, which includes email but not e.g. name Mar 16, 2023 at 12:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.