Ril*_*ley 2 node.js google-drive-api
我正在尝试使用服务帐户通过 NodeJS 服务器连接到 Google Drive API。目标是让服务器能够以服务帐户身份进行身份验证、从驱动器检索相关文件并将其发送回用户,而无需用户直接登录 Google。这将使我能够通过网络应用程序控制文件访问,而不必通过云端硬盘手动共享和取消共享文件。根据我对 Google Drive API 的理解,这应该都是可能的。问题是我什至不知道如何验证我的服务器。服务器在AWS EC2实例上运行。澄清一下,我不希望用户必须使用前端界面进行身份验证。
我已按照快速入门指南进行操作,并按照此处的说明设置了服务帐户和密钥,但是在按照第二个链接中的说明创建密钥后,我似乎没有正确的credentials.json文件。在 Google 开发者控制台上生成密钥后获得的 JSON 文件具有以下对象密钥(有意删除的值):
type,,,,,,,,,,,,,project_idprivate_key_idprivate_keyclient_emailclient_idauth_uritoken_uriauth_provider_x509_cert_urlclient_x509_cert_url快速入门指南建议该文件应包含client_secret并redirect_uris位于某个installed对象 ( const {client_secret, client_id, redirect_uris} = credentials.installed;) 内:
尝试运行此快速入门文件会导致抛出index.js错误,因为. 在哪里可以生成必要的凭据文件?或者我完全走错了路?installedcredentials.json
像这样的帖子引用了旧版本的快速入门文档上的类似问题,但这里的解决方案没有帮助,因为client_secret我的凭据文件中没有密钥。
当我看到您文件的显示密钥时credentials.json,我了解到该文件是服务帐户的凭据文件。如果我的理解是正确的,当我看到你的显示脚本时,该脚本似乎是针对 OAuth2 的。在这种情况下,该脚本不能用于服务帐户。我认为这就是您当前问题的原因。
为了使用服务帐户使用 Drive API,以下示例脚本怎么样?
在使用此脚本之前,请先设置credentialFilename服务帐户。在这种情况下,请包含路径。
const { google } = require("googleapis");
const credentialFilename = "credentials.json";
const scopes = ["https://www.googleapis.com/auth/drive.metadata.readonly"];
const auth = new google.auth.GoogleAuth({keyFile: credentialFilename, scopes: scopes});
const drive = google.drive({ version: "v3", auth });
// This is a simple sample script for retrieving the file list.
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;
console.log(files);
}
);
Run Code Online (Sandbox Code Playgroud)
https://www.googleapis.com/auth/drive.metadata.readonly范围。请根据您的实际情况进行修改。| 归档时间: |
|
| 查看次数: |
3993 次 |
| 最近记录: |