簡體   English   中英

如何從 OAuth2 Google API 獲取電子郵件和個人資料信息?

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

我正在嘗試使用 OAuth2 API 使用 Google API Node.js 客戶端檢索登錄用戶的名稱。

按照用法示例,我設法進行了登錄,但找不到獲取個人資料信息的方法。

我沒有使用 People API 或 Plus API,因為據我所知,OAuth2 包括https://www.googleapis.com/auth/userinfo.profile ,這應該足以完成任務。

我已經看到了一些類似的問題並嘗試了這個的解決方案但是它沒有用,也許它太舊了(?)

使用 npm 包 googleapis 如何在驗證用戶身份后獲取用戶的電子郵件地址?

查看其他 API,例如 Google 表格,可以這樣調用它們的函數:

var google = require('googleapis');
var sheets = google.sheets('v4');

...

sheets.spreadsheets.values.get({
    auth: auth,
    spreadsheetId: file_id,
    range: my_ranges,
  }, function(err, response){
       ...
     }
);

但似乎 OAuth2 不是那樣工作的......

您可以使用 node.js 的快速入門。 詳細信息是https://developers.google.com/gmail/api/quickstart/nodejs 使用 Quickstart 中的示例腳本,您可以通過 OAuth2 檢索訪問令牌,並檢索電子郵件和用戶配置文件。

在運行 Quickstart 示例之前,請確認先決條件、步驟 1 和步驟 2。

您可以通過如下更改listLabels(auth)來使用。 范圍是https://www.googleapis.com/auth/gmail.readonly

腳本:

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檢索用戶配置文件。
  • gmail.users.messages.get檢索電子郵件。

如果我誤解了你的問題,我很抱歉。

添加:

請將上面的腳本更改為以下腳本。 范圍是https://www.googleapis.com/auth/userinfo.profile

腳本:

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);
    }
});

結果:

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

2021年解決方案

這個答案可能會偏離最初提出的問題,但我認為這對於某些通過生成 AuthUrl 並將其發送到客戶端然后在回調 URL 中接收數據響應而在后端獲取 google 用戶信息的人很有用用戶從客戶端授予權限。

一些全局聲明

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

使用范圍生成 Auth URL

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

在回調中獲取用戶數據

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

如果有任何混淆或錯誤,請隨時在評論中討論

您還可以查看 PassportJS。 他們有多種策略,包括 OAuth2 和 3 種不同的 Google Auth 策略。 我的回答並沒有真正回答您的問題,但即使看一眼 Passport 的代碼,您也可能會得到答案。

http://passportjs.org/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM