使用JWT和googleapis进行身份验证时出错(错误:0906D06C:PEM例程:PEM_read_bio:无起始行)

时间:2018-08-24 19:39:42

标签: node.js google-api google-analytics-v4 google-api-nodejs-client

我正尝试从我的Node服务器(作为Firebase Cloud Function运行)连接到Google Analytics Reporting API v4。按照此示例,我想使用JWT进行身份验证:http://nali.org/google-analytics-v4-api-node-js-starter-example/

但是我遇到此错误:

Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
    at Error (native)
    at Sign.sign (crypto.js:307:26)
    at Object.sign (/user_code/node_modules/googleapis/node_modules/jwa/index.js:76:45)
    at Object.jwsSign [as sign] (/user_code/node_modules/googleapis/node_modules/jws/lib/sign-stream.js:32:24)

似乎它试图使用PEM文件,但我只想使用电子邮件和私钥。这不可能吗?是我给的示例链接误导了吗?

这是我的代码:

const email = functions.config().ga.email;
const privateKey = functions.config().ga.privatekey;
const scope = ['https://www.googleapis.com/auth/analytics.readonly'];
const token = new googleapis.google.auth.JWT(email, null, privateKey, scope, null);

token.authorize( (error, tokens) => {
  if (error) {
    console.error('Error connecting to GA:', error);
  } else {
    console.log('Authorized!', tokens);
  }
})

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

菜鸟错误:我没有在我的privateKey字符串中转义\nfirebase functions:config:set正在将\n转换为\\n的固定代码如下:

const email = functions.config().ga.email;
const privateKey = _.replace(functions.config().ga.privatekey, /\\n/g, '\n');
const scope = ['https://www.googleapis.com/auth/analytics.readonly'];
const jsonWebToken = new googleapis.google.auth.JWT(email, null, privateKey, scope, null);

jsonWebToken.authorize( (error, tokens) => {
  if (error) {
    console.error('Error connecting to GA:', error);
  } else {
    console.log('Authorized!', tokens);
  }
});

我的实际问题已通过以下建议得到解决:Escaping issue with firebase privateKey as a Heroku config variable