如何使用 Nodejs 在没有 OAuth 的情况下使用 Google Drive API?

cla*_*ine 4 google-api node.js google-drive-api google-oauth google-api-nodejs-client

在搜索 stackoverflow、博客、YouTube、Google Drive API 文档等后,大多数示例都展示了如何通过 OAuth 使用 Drive API。

\n

我想构建一个 Nodejs 应用程序,只有当新用户在我的应用程序中创建帐户时,Nodejs 服务器才会在 Google Drive 上创建电子表格。然后该电子表格将可供应用程序管理员使用。

\n

这是一个服务器端进程,因此不需要 OAuth 同意屏幕等

\n

有没有办法仅通过 API 密钥和 REST URL\xe2\x80\x99s 使用 Drive API

\n

下面的 Google 文档链接提供了仅使用 REST URL\xe2\x80\x99s 与 Drive API 交互的示例。

\n

https://developers.google.com/drive/api/v3/reference/files/create

\n

Google 文档对于如何使用上面链接中的 API 密钥和 REST URL\xe2\x80\x99s 的 Drive API 含糊其辞,因为示例使用 REST URL\xe2\x80\x99s 来创建文件等

\n

DaI*_*mTo 5

首先您需要了解私有数据和公共数据之间的区别。

\n

公共数据是不为任何人所拥有的数据。一个很好的例子是公共 YouTube 视频。您不需要所有者的许可即可查看此视频,您可以使用公共 api 密钥访问搜索视频列表方法,并且您将能够访问它们。

\n

私有数据是用户拥有的数据。您的谷歌云端硬盘帐户是私人用户数据。只有您可以访问它。只有您可以授予应用程序访问它的权限。

\n

公共 api 密钥只能用于访问公共数据。要访问私人用户数据,您需要获得所有者的同意

\n

如果您检查文档,您会发现它准确地告诉您这一点,您想使用file.create方法。

\n

在此输入图像描述

\n

您需要获得授权,并且用户必须同意至少其中一个范围,您才能使用该方法。

\n

因此,要回答您的问题,Is there not a way to use the Drive API with just API keys and REST URL\xe2\x80\x99s 答案是“不”,没有。不使用 api 密钥。

\n

不过我还有一个选择。您的应用程序将连接到开发人员控制的帐户。这意味着您可以使用服务帐户。服务帐户就像虚拟用户,如果配置正确,您可以通过与服务帐户共享文件夹来授予其对驱动器帐户上文件夹的访问权限,就像与任何其他用户一样。完成此操作后,服务帐户将能够从您的服务器访问该驱动器帐户,而无需您进行其他交互。

\n
// service account key file from Google Cloud console.\nconst KEYFILEPATH = \'C:\\\\Youtube\\\\dev\\\\ServiceAccountCred.json\';\n\n// Request full drive access.\nconst SCOPES = [\'https://www.googleapis.com/auth/drive\'];\n\n// Request full drive scope and profile scope, giving full access to google drive as well as the users basic profile information.\nconst SCOPES = [\'https://www.googleapis.com/auth/drive\', \'profile\'];\n// Create a service account initialize with the service account key file and scope needed\nconst auth = new google.auth.GoogleAuth({\n    keyFile: KEYFILEPATH,\n    scopes: SCOPES\n});\nconst driveService = google.drive({version: \'v3\', auth});\nlet fileMetadata = {\n        \'name\': \'icon.png\',\n        \'parents\':  [  \'10krlloIS2i_2u_ewkdv3_1NqcpmWSL1w\'  ]\n    };\nlet response = await driveService.files.create({\n    resource: fileMetadata,\n    media: media,\n    fields: \'id\'\n});\nswitch(response.status){\n    case 200:\n        let file = response.result;\n        console.log(\'Created File Id: \', response.data.id);\n        break;\n    default:\n        console.error(\'Error creating the file, \' + response.errors);\n        break;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

使用 Node Js无耻地将代码从上传图像复制到 Google 驱动器

\n