Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...

like image 242
amlibtest Avatar asked Apr 26 '17 21:04

amlibtest


People also ask

How can I get user information from OAuth?

If the authorization server supports OpenID Connect, there are two standard ways to get user information. One is to request the authorization server to issue an ID token which contains user information. The other is to access UserInfo Endpoint. See OpenID Connect Core 1.0 for details.


3 Answers

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: '#####'
}
like image 70
Tanaike Avatar answered Nov 15 '22 17:11

Tanaike


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/

like image 29
Clayton Ray Avatar answered Nov 15 '22 16:11

Clayton Ray


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

like image 31
wingman__7 Avatar answered Nov 15 '22 17:11

wingman__7