GoogleApis:无法使用服务帐户json文件进行身份验证

时间:2020-10-07 20:05:40

标签: node.js google-api

我正在尝试验证Gmail api的Node.js应用程序(最终将成为Express.js后端的一部分)。在我的.env文件中,我已在Env变量GOOGLE_APPLICATION_CREDENTIALS下设置了certificate.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.

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

1 个答案:

答案 0 :(得分:0)

根据官方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);
  }
}