通过服务帐户访问Google云端硬盘:错误:需要登录

时间:2020-07-04 22:21:33

标签: node.js google-drive-api google-oauth service-accounts

const {google} = require('googleapis');
let drive = google.drive('v3');

exports.handler = async (req, res) => {
    res.set('Access-Control-Allow-Origin', '*')
      .set('Access-Control-Allow-Methods', 'POST')
    .status(200);
  var privatekey 
  var jwtClient 
  await global.admin.database().ref(`g_drive_token/OfficServiceAccount`).once('value').then((doc)=> {
    privatekey = doc.val()
    jwtClient = new google.auth.JWT(
      privatekey.client_email,
      null,
      privatekey.private_key,
      ['https://www.googleapis.com/auth/drive.file'],
      null);
      console.log(JSON.stringify(jwtClient))   
      authWithServicePrivateKey(jwtClient)
      return "null"
    }) .catch((error)=> {            
    console.log('Error fetching user data:+', error);
      return "null"
  }) 


function authWithServicePrivateKey(jwtClient){
  //authenticate request
jwtClient.authorize(function (err, tokens) {
    if (err) {
      console.log("Could not connect***!"+err);
      return;
    } else {
      console.log("Successfully connected!");
      console.log('token******'+JSON.stringify(tokens))
      listFolderInGoogleDrive()
      CreateFolderInGoogleDrive()
    }
   });
}


//Google Drive API
function listFolderInGoogleDrive() {
    console.log('listFolderInGoogleDrive() was called')
    drive.files.list({
        auth: jwtClient,
        pageSize: 10,
        fields: 'nextPageToken, files(id, name)',
      }, (err, res) => {
        if (err) return console.log('The API returned an error: ' + err);
        console.log(JSON.stringify(res.data))
        console.log(JSON.stringify(res.data.files))
        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.');
        }
      });
    }

    function  CreateFolderInGoogleDrive() {
        console.log('CreateFolderInGoogleDrive() was called')
        var fileMetadata = {
            auth: jwtClient,
            'name': 'OfficService',
            'mimeType': 'application/vnd.google-apps.folder',
            'parents':['12CCq1GGoTyDW_Ox09TZf5BDgaPAjB0AR']
          };
          drive.files.create({
            resource: fileMetadata,
            fields: 'id'
          },(err, file)=> {
            if (err) {
              // Handle error
              console.error(err);
            } else {
             console.log('***parent****'+ file.data.id) 
           
            }
          });
        }

注意:驱动器文件夹“ 12CCq1GGoTyDW_Ox09TZf5BDgaPAjB0AR”已与服务帐户电子邮件ID共享。

以下是控制台日志的一些结果,它们反映了失败的地方。

令牌****** {“ access_token”:“ **********”,“ token_type”:“承载者”,“到期日期”:1593865140000,“ refresh_token”:“ jwt占位符“}

listFolderInGoogleDrive()被称为

CreateFolderInGoogleDrive()被称为

错误:需要登录

我想,我没有使用令牌进行身份验证。请使用Node.js代码帮助我,以使用此令牌来验证服务帐户。

1 个答案:

答案 0 :(得分:3)

我想修改以下修改。

修改点:

  • exports.handler = async (req, res) => {},不使用最后一个}。因此您的脚本不完整。请注意这一点。
    • 从您的问题来看,我认为这可能是脚本的未命中副本。
  • 在您的脚本中,jwtClientlistFolderInGoogleDrive()上未使用CreateFolderInGoogleDrive()。我认为这可能是您遇到问题的原因。
  • CreateFolderInGoogleDrive()的{​​{1}}对象中必须使用auth: jwtClient
    • 但是在这种情况下,我想像{resource: fileMetadata, fields: "id"}一样在jwtClient中包括drive

当以上几点反映到您的脚本中时,它如下所示。在这种情况下,google.drive({ version: "v3", auth: jwtClient })authWithServicePrivateKeylistFolderInGoogleDrive的功能将被修改。

修改后的脚本:

CreateFolderInGoogleDrive

注意:

  • 在此修改中,它假设您已经能够使用带有服务帐户的Drive API来获取和放置Google云端硬盘的值。请注意这一点。

已添加:

当您要检索手动创建的文件的文件列表时,请按如下所示修改范围。

发件人:

function authWithServicePrivateKey(jwtClient) {
  // Modified
  jwtClient.authorize(function (err) {
    if (err) {
      console.log("Could not connect***!" + err);
      return;
    }
  });
  drive = google.drive({ version: "v3", auth: jwtClient }); // Added
  listFolderInGoogleDrive();
  CreateFolderInGoogleDrive();
}

//Google Drive API
function listFolderInGoogleDrive() {
  console.log("listFolderInGoogleDrive() was called");
  drive.files.list(
    {
      //   auth: jwtClient,  // Removed
      pageSize: 10,
      fields: "nextPageToken, files(id, name)",
    },
    (err, res) => {
      if (err) return console.log("The API returned an error: " + err);
      console.log(JSON.stringify(res.data));
      console.log(JSON.stringify(res.data.files));
      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.");
      }
    }
  );
}

function CreateFolderInGoogleDrive() {
  console.log("CreateFolderInGoogleDrive() was called");
  var fileMetadata = {
    // auth: jwtClient,  // Removed
    name: "OfficService",
    mimeType: "application/vnd.google-apps.folder",
    parents: ['12CCq1GGoTyDW_Ox09TZf5BDgaPAjB0AR'],
  };
  drive.files.create(
    {
      resource: fileMetadata,
      fields: "id",
    },
    (err, file) => {
      if (err) {
        // Handle error
        console.error(err);
      } else {
        console.log("***parent****" + file.data.id);
      }
    }
  );
}

收件人:

['https://www.googleapis.com/auth/drive.file'],
  • 关于['https://www.googleapis.com/auth/drive'], 的范围,the official document如下所述。

    按文件访问由应用程序创建或打开的文件。文件授权是按用户授予的,并且在用户取消对应用程序的授权时将其撤销。

此外,您只想检索https://www.googleapis.com/auth/drive.file共享文件夹的文件列表,请进行以下修改。

发件人:

12CCq1GGoTyDW_Ox09TZf5BDgaPAjB0AR

收件人:

drive.files.list({
    auth: jwtClient,
    pageSize: 10,
    fields: 'nextPageToken, files(id, name)',
  }, (err, res) => {