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

时间:2019-05-24 09:38:16

标签: node.js google-api

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

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来获取令牌,但是如何将其放置在代码中以及如何使用它?

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的计算服务实现了。该示例指出:

  

例如,当您的代码在本地开发人员计算机上运行时,将创建JWT auth客户端;当在已配置的Google Compute Engine实例上运行相同的代码时,将创建Compute客户端。

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应用程序使用我的驱动器,而无需我每次允许其访问。

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

1 个答案:

答案 0 :(得分:1)

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

我还在互联网上的某些页面上读到了您无法共享“ Team Drive”的信息,但也许您可以将服务帐户添加为团队成员。

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


// 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内,您可以找到服务帐户的电子邮件地址,然后可以尝试将其添加到“ Team Drive”中。