【问题标题】:NodeJS Googleapis Service Account authenticationNodeJS Googleapis 服务帐号认证
【发布时间】:2022-05-24 18:19:36
【问题描述】:

我正在尝试使用服务帐户对 GoogleAPI 执行身份验证。我设置了一个服务帐户,其凭据位于credentials.json。我尝试访问一个私人工作表,我在其中添加了具有编辑权限的服务帐户的电子邮件地址。

这里是我使用的代码:

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

let scopes = ['https://www.googleapis.com/auth/spreadsheets'];
let credentials = require("./credentials.json");

const authClient = new google.auth.JWT(
    credentials.client_email,
    null,
    credentials.private_key,
    scopes);

authClient.authorize(function(err, tokens) {
    if (err) {
        console.log(err);
        return;
    } else {
        authClient.setCredentials(tokens);
    }
});

const sheets = google.sheets({
    version: 'v4',
    authClient
});

let spreadsheetId = //...
let range = //...

const request = {
    spreadsheetId: spreadsheetId,
    range: range
};

sheets.spreadsheets.values.get(request, function(err, response) {
    if (err) {
        console.log('The API returned an error: ' + err);
    } else {
        console.log('Result: ' + response);
    }
});

我猜 API 会随着时间的推移而改变,因为许多指南展示了不同的方法,最终没有一个对我有用。 错误如下:

The API returned an error: Error: The request is missing a valid API key.

据我了解,一个简单的 API 密钥应该只用于在公共工作表上进行未经身份验证的访问,所以我不明白为什么它甚至需要它。如果我添加这样的 API 密钥,我会收到错误

The API returned an error: Error: The caller does not have permission

使用

$ npm list googleapis
`-- googleapis@52.1.0

任何帮助将不胜感激。

【问题讨论】:

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


    【解决方案1】:

    对于那些在 2022 年仍然在 NodeJS 运行时面临googleapis 问题的人。

    • 首先,重定向到Google-IAM-Admin/ServiceAccount 以选择当前工作项目。
    • 其次,点击跳转到Service Account,格式如下project@sub-name-id.iam.gserviceaccount.com
    • 第三,在[Details, Permissions, Keys, Metrics, Logs]之间。跳转到 Keys 然后 Add Key -> Create new Key -> Key type::JSON 并将 JSON 文件保存到您的计算机。

    在 NodeJS 运行时中,我使用以下语义版本 googleapis@100.0.0

    • 您可以创建 JWT 客户端并在 google.options({auth: client}); 处注入谷歌默认身份验证,或者将身份验证客户端提供给特定服务作为 google.chat({version: 'v1', auth: client});
    • 但是,在以下示例中。我创建了一个GoogleAuth 实例,然后创建了一个AuthClient。这导致 JWT 方法的行为相同。
    /** Import Node Native Dependencies !*/
    import * as path from "path";
    
    /** Import ES6 Default Dependencies !*/
    import {google} from "googleapis";
    
    const {client_email, private_key} = require('$/keys/credentials.json');
    
    /**
     ** @description - Google [[Service Account]] Authenticator.
     **/
    const auth = new google.auth.GoogleAuth({
        keyFile: path.resolve('keys/credentials.json'),
        /** Scopes can be specified either as an array or as a single, space-delimited string; ~!*/
        scopes: [
            "https://www.googleapis.com/auth/chat.bot",
        ],
    });
    
    const client = new google.auth.JWT({
        email: client_email,
        key: private_key,
        /** Scopes can be specified either as an array or as a single, space-delimited string; ~!*/
        scopes: [
            "https://www.googleapis.com/auth/chat.bot",
        ],
    });
    
    (async () => {
        /** @description - Either [[Get Client]] from [Google Auth] or Use directly from [JWT Client] ~!*/
        const client = await auth.getClient();
        /** @description - Use this Authorized Client as Default Authenticated to fallback from [Non-Authenticated Services] ~!*/
        google.options({auth: client});
    
        const chat = google.chat({
            version: 'v1',
            /** @description - Provide [Authenticated Services] to [Google Chat Service] Instance ~!*/
            auth: client,
        });
    
        const response = await chat.spaces.members.get({
            // Required. Resource name of the attachment, in the form "spaces/x/messages/x/attachments/x".
            name: 'spaces',
        });
        console.log('response', response.data);
    
        return void 0;
    })();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多