NodeJS 如何获取电子邮件ID作为google oauth 2.0的一部分googldrive登录

lokaqttq  于 2022-12-03  发布在  Node.js
关注(0)|答案(1)|浏览(96)

我正在创建一个网站,其中在一个页面谷歌驱动器登录是必需的。我正在使用谷歌的OAuth 2.0。我已经使用了以下范围

https://www.googleapis.com/auth/drive.metadata.readonly
 
https://www.googleapis.com/auth/drive

当我尝试打印信息时,电子邮件显示为空。我不希望电子邮件为空。它需要有谷歌驱动器中的签名电子邮件我如何获得它?
我试过用

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

但即使这样,电子邮件也不会显示

const {google} = require('googleapis');

const oauth2Client = new google.auth.OAuth2(
  CLIENT_ID,
  CLIENT_SECRET,
  REDIRECT_URL
);

const scopes = [
  'https://www.googleapis.com/auth/drive.metadata.readonly',
  'https://www.googleapis.com/auth/drive',
  'https://www.googleapis.com/auth/userinfo.email'
];

const authorizationUrl = oauth2Client.generateAuthUrl({
  access_type: 'offline',
  scope: scopes,
});
wyyhbhjk

wyyhbhjk1#

我不知道你所说的用户的email id是什么意思。但是about.get方法返回了一些关于用户的基本信息。如果你真的在寻找用户的email地址,那么about.get就返回了。还有一个权限id,它可能是也可能不是google本身的用户id,我从来没有真正费心去仔细检查过。

// npm install googleapis@105 @google-cloud/local-auth@2.1.0 --save
// npm install googleapis

const fs = require('fs').promises;
const path = require('path');
const process = require('process');
const {authenticate} = require('@google-cloud/local-auth');
const {google} = require('googleapis');

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive'];

// Token File Name
const TOKEN_FILE = 'quickstart_about_email.json'

// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = path.join(process.cwd(), TOKEN_FILE);
const CREDENTIALS_PATH = 'C:\\Development\\FreeLance\\GoogleSamples\\Credentials\\CredWebEverything.json';

/**
 * Reads previously authorized credentials from the save file.
 *
 * @return {Promise<OAuth2Client|null>}
 */
async function loadSavedCredentialsIfExist() {
    try {
        const content = await fs.readFile(TOKEN_PATH);
        const credentials = JSON.parse(content);
        return google.auth.fromJSON(credentials);
    } catch (err) {
        return null;
    }
}

/**
 * Serializes credentials to a file comptible with GoogleAUth.fromJSON.
 *
 * @param {OAuth2Client} client
 * @return {Promise<void>}
 */
async function saveCredentials(client) {
    const content = await fs.readFile(CREDENTIALS_PATH);
    const keys = JSON.parse(content);
    const key = keys.installed || keys.web;
    const payload = JSON.stringify({
        type: 'authorized_user',
        client_id: key.client_id,
        client_secret: key.client_secret,
        refresh_token: client.credentials.refresh_token,
    });
    await fs.writeFile(TOKEN_PATH, payload);
}

/**
 * Load or request or authorization to call APIs.
 *
 */
async function authorize() {
    let client = await loadSavedCredentialsIfExist();
    if (client) {
        return client;
    }
    client = await authenticate({
        scopes: SCOPES,
        keyfilePath: CREDENTIALS_PATH,
    });
    if (client.credentials) {
        await saveCredentials(client);
    }
    return client;
}

/**
 * Lists the names and IDs of up to 10 files.
 * @param {OAuth2Client} authClient An authorized OAuth2 client.
 */
async function getUserEmail(authClient) {
    const drive = google.drive({version: 'v3', auth: authClient});
    const res = await drive.about.get({
        pageSize: 10,
        fields: 'user(emailAddress)',
    });    

    // print users email
    console.log(`Email: ${res.data.user.emailAddress}`);

}

authorize().then(getUserEmail).catch(console.error);

相关问题