我想构建一个使用google sheet api创建,读取和编写电子表格的api服务 . 使用express.js将api服务部署在firebase Cloud 功能上,我创建了服务帐户,并使用JWT进行身份验证 . api在本地测试时有效(即可以创建,读取和写入电子表格),但在部署到firebase Cloud 功能时失败 .

const functions = require('firebase-functions');

// firebase admin
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

// google sheet api
const google = require('googleapis');
const key = require('./key/serviceKey.json');

const scopes = [
  'https://www.googleapis.com/auth/spreadsheets',
  'https://www.googleapis.com/auth/drive'  
];

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

authClient.authorize((err, tokens) => {
  if (err) {
    console.log('error occurred when authorising with JWT');
  } else {
    console.log('auth success, tokens', tokens);
    google.options({ auth: authClient });
  }
});

const drive = google.drive('v2');
const sheets = google.sheets('v4');

我在firebase Cloud 功能上测试时收到的错误消息:

请求缺少必需的身份验证凭据 . 预期的OAuth 2访问令牌,登录cookie或其他有效的身份验证凭据 .

最终,我将使用一个离子应用程序调用api来执行某些操作(例如,与其他用户创建和共享电子表格) . 我正在采取正确的方法,还是应该使用其他类型的身份验证?

我的功能定义:

const functions = require('firebase-functions');
const express = require('express');
const cors = require('cors')({ origin: true });
const bodyParser = require('body-parser');
const app = express();
app.use(cors);
app.use(bodyParser.json({ type: 'application/json' }));

// some routing setup

exports.api = functions.https.onRequest(app);

路由器设置:

const express = require('express');
const router = express.Router();
router.post('/createSheets', (req, res) => {
  const request = { // }
  sheets.spreadsheets.create(request, (err, sheetsResponse) => {
    // some code
  }
});