node.js - 如何使用 Google 服务帐户代替 oAuth2Client 来使用 Google Apps API?

标签 node.js google-api

我已成功使用 oAuth2Client 与 Node 使用 Google's Quickstart tutorial :

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

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'];
// 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 = 'token.json';

// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Google Drive API.
  authorize(JSON.parse(content), listFiles);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getAccessToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getAccessToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

/**
 * Lists the names and IDs of up to 10 files.
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listFiles(auth) {
  const drive = google.drive({version: 'v3', auth});
  drive.files.list({
    pageSize: 10,
    fields: 'nextPageToken, files(id, name)',
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    const files = res.data.files;
    if (files.length) {
      console.log('Files:');
      files.map((file) => {
        console.log(`${file.name} (${file.id})`);
      });
    } else {
      console.log('No files found.');
    }
  });
}

但是,我想避免同意屏幕并进行服务到服务身份验证。

我找到了Node GToken获取 token ,但我应该将其放在代码中的什么位置以及如何使用它?

const key = '-----BEGIN RSA PRIVATE KEY-----\nXXXXXXXXXXX...';
const { GoogleToken } = require('gtoken');
const gtoken = new GoogleToken({
  email: 'my_service_account_email@developer.gserviceaccount.com',
  scope: ['https://scope1', 'https://scope2'], // or space-delimited string of scopes
  key: key
});

我还发现了以下有关如何实现 Service to Service Authentication 的代码,但它似乎是为 Google 的计算服务实现的。该示例指出:

For example, a JWT auth client will be created when your code is running on your local developer machine, and a Compute client will be created when the same code is running on a configured instance of Google Compute Engine.

const {google} = require('googleapis');
const compute = google.compute('v1');

async function main () {
  // This method looks for the GCLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS
  // environment variables.
  const auth = await google.auth.getClient({
    // Scopes can be specified either as an array or as a single, space-delimited string.
    scopes: ['https://www.googleapis.com/auth/compute']
  });

  // obtain the current project Id
  const project = await google.auth.getProjectId();

  // Fetch the list of GCE zones within a project.
  const res = await compute.zones.list({ project, auth });
  console.log(res.data);
}

main().catch(console.error);

我在其他网站上找到了使用 googleapis.auth.JWT 的代码,但我找不到与 Google Apps 一起使用的服务帐户相关的任何文档。

Here it says that a service account isn't what's needed.不幸的是,如果答案也适用于我的情况,我不明白要理解的问题是什么。我想要做的是授权我的 node.js 应用程序使用我的驱动器,而不需要我每次都允许它访问。

我不知道如何翻译快速入门代码以适应服务帐户。

最佳答案

我无权访问“Google Drive for Business”帐户,因此我发布了我可以使用我的个人 Google 云端硬盘(“我的云端硬盘”)执行的操作。

我还在 Internet 上的某些页面上看到您无法共享“团队云端硬盘”,但也许您可以将服务帐户添加为团队成员。

在我与服务帐户共享文件夹后,此代码会列出“我的云端硬盘”上的文件夹中的文件。


// load library
const { google } = require('googleapis');

// configure a JWT auth client
const privatekey = require("./privatekey.json");

const jwtClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    [
        'https://www.googleapis.com/auth/drive.readonly',
        'https://www.googleapis.com/auth/drive.metadata.readonly'
    ]
);

jwtClient.authorize()
    .then(function (tokens) {
        // console.log(tokens);
        console.log("Authentication successfull.\n");

        // list the files once authenticated
        listFiles(jwtClient);
    })
    .catch(function (error) {
        throw (error);
    });


function listFiles(auth) {
    const drive = google.drive({ version: 'v3', auth });
    drive.files.list({
        pageSize: 10,
        fields: 'nextPageToken, files(id, name)',
        // q: "name contains 'foo'"
    })
        .then(res => {
            console.log(res.data);
        })
        .catch(err => console.log(err));

}



privatekey.json 是从“Google Cloud Platform”(当然启用了“Google Drive API”)的服务帐户(下载并重命名)的私钥。

privatekey.json 中,您可以找到服务帐户的电子邮件地址,然后您可以尝试将其添加到“团队云端硬盘”。

关于node.js - 如何使用 Google 服务帐户代替 oAuth2Client 来使用 Google Apps API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56289839/

相关文章:

google-api - 将 oauth2 与 native (iOS/Android) 移动应用程序集成

google-api - 为什么 Google 的 YouTube Data API v3 "Queries per day"配额增加量比我调用的要多?

javascript - 如何获取系统命令的输出作为函数的返回值?

javascript - Node js 和 Redis 未定义的 JSON 属性

node.js - 将文件编码为 base 64 Nodejs

java - 如何使用 google spreadsheet api 获取列名列表?

node.js - 一个 Redis 连接可以为一千个并发用户提供服务吗?

node.js - 所需路径可以来自项目根目录而不是相对路径吗?

javascript - 使用 Google Drive v3 更新文件内容 (JavaScript)

javascript - 使用服务帐户访问 Google Analytics API