【问题标题】:GoogleApis: Unable to authenticate using service account json fileGoogleApis:无法使用服务帐户 json 文件进行身份验证
【发布时间】:2020-10-07 20:05:40
【问题描述】:

我正在尝试为 gmail api 验证 Node.js 应用程序(最终将成为 Express.js 后端的一部分)。在我的 .env 文件中,我在 Env 变量 GOOGLE_APPLICATION_CREDENTIALS 下设置了 credentials.json 文件的绝对路径。

然后我尝试运行一个简单的函数来打印消息列表

async function runSample() {
  <message setup removed>

  try {
    const res = await gmail.users.messages.send({
      userId: 'me',
      requestBody: {
        raw: encodedMessage,
      },
    });

    console.log(res.data);
    return res.data;
  } catch (error) {
    throw new Error(error);
  }
}

runSample();

// (node:15522) UnhandledPromiseRejectionWarning:
// Error: Error: Login Required.

我认为此身份验证流程不需要明确的范围授权或登录。如果不正确,需要进行哪些更改来处理登录?

【问题讨论】:

    标签: node.js google-api


    【解决方案1】:

    根据官方docs,需要通过oAuth2授权,还要指定范围

    const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
    
    const TOKEN_PATH = 'token.json';
    
    
    fs.readFile('credentials.json', (err, content) => {
      if (err) return console.log('Error loading client secret file:', err);
      authorize(JSON.parse(content), runSample);  // this is important
    });
    
    /**
     * 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 getNewToken(oAuth2Client, callback);
        oAuth2Client.setCredentials(JSON.parse(token));
        callback(oAuth2Client);
      });
    }
    
    
    async function runSample(auth) {
    
    
      const gmail = google.gmail({version: 'v1', auth});
    
    
      try {
        const res = await gmail.users.messages.send({
          userId: 'me',
          requestBody: {
            raw: encodedMessage,
          },
        });
    
        console.log(res.data);
        return res.data;
      } catch (error) {
        throw new Error(error);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-24
      • 2020-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多