How to get email and profile information from OAuth2 Google API?

12,098

Solution 1

You can use Quickstart for node.js. The detail information is https://developers.google.com/gmail/api/quickstart/nodejs. Using a sample script from Quickstart, you can retrieve access token by OAuth2, and retrieve email and user profile.

Before it runs a sample of Quickstart, please confirm Prerequisites, Step 1 and Step 2.

You can use by changing listLabels(auth) as follows. The scope is https://www.googleapis.com/auth/gmail.readonly.

Script :

var gmail = google.gmail({
        auth: auth,
        version: 'v1'
});

gmail.users.getProfile({
    auth: auth,
    userId: 'me'
    }, function(err, res) {
    if (err) {
        console.log(err);
    } else {
        console.log(res);
    }
});

gmail.users.messages.get({
    'userId': 'me',
    'id': 'mail ID',
    'format': 'raw'
}, function (err, res) {
    console.log(new Buffer(res.raw, 'base64').toString())
});
  • gmail.users.getProfile retrieves user profile.
  • gmail.users.messages.get retrieves email.

If I misunderstand your question, I'm sorry.

Added :

Please change above to following script. Scope is https://www.googleapis.com/auth/userinfo.profile.

Script :

var oauth2 = google.oauth2({
        auth: auth,
        version: 'v2'
});

oauth2.userinfo.v2.me.get(
function(err, res) {
    if (err) {
        console.log(err);
    } else {
        console.log(res);
    }
});

Result :

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

Solution 2

You can also look into PassportJS. They have multiple strategies, including OAuth2 and 3 different Google Auth strategies. My answer doesn't really answer your question but maybe even taking a peek at Passport's code, you may get your answer.

http://passportjs.org/

Solution 3

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);    // you will find name, email, picture etc. here

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

Share:
12,098
amlibtest
Author by

amlibtest

Updated on June 08, 2022

Comments

  • amlibtest
    amlibtest almost 2 years

    I'm trying to retrieve the name of a logged in user using Google API Node.js Client, using OAuth2 API.

    Following the usage example, I managed to do the login, but I can't find a way to get the profile information.

    I'm not using People API nor Plus API, cause as far as i know, OAuth2 includes https://www.googleapis.com/auth/userinfo.profile, which should be enough for the task.

    I have seen some similar questions and tried the solutions of this one but it didn't work, maybe it's too old (?)

    With the npm package googleapis how do I get the user's email address after authenticating them?

    Looking at other API's like Google Sheets, it's possible to call their functions like this:

    var google = require('googleapis');
    var sheets = google.sheets('v4');
    
    ...
    
    sheets.spreadsheets.values.get({
        auth: auth,
        spreadsheetId: file_id,
        range: my_ranges,
      }, function(err, response){
           ...
         }
    );
    

    But it seems that OAuth2 doesn't work like that...

  • amlibtest
    amlibtest about 7 years
    I appreciate your answer, but my problem is not the authentication. Looking at Passport.js, I see that OAuth is not the same as OpenID. Good to know
  • amlibtest
    amlibtest about 7 years
    I'm not really sure this is the answer I'm looking for. As I stated before, I have the scopes for googleapis.com/auth/userinfo.profile and googleapis.com/auth/userinfo.email, so do I really need to include gmail scopes even if I'm not going to check messages?
  • amlibtest
    amlibtest about 7 years
    Looking at gmail.users.getProfile response, it has the email address, id, total messages and total threads, but nothing about the user profile information. So I'm afraid I can't accept this as the correct answer
  • Tanaike
    Tanaike about 7 years
    I'm so sorry my misunderstand. I updated my answer as "Added". Please check it. The sample retrieves user information using oauth2.userinfo.get.
  • amlibtest
    amlibtest about 7 years
    Thank you, it works. I can see this is not really different from the answer on the link on my question, maybe I did a mistake and didn't notice about
  • Tanaike
    Tanaike about 7 years
    Welcome. I'm glad I could help.