Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error authenticating with JWT and googleapis (error:0906D06C:PEM routines:PEM_read_bio:no start line)

I am trying to connect to Google Analytics Reporting API v4 from my Node server (running as a Firebase Cloud Function). I want to authenticate using JWT, as per this example: http://nali.org/google-analytics-v4-api-node-js-starter-example/

However I am getting this error:

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)

It seems like its trying to use a PEM file, but I just want to use the email and private key. Is this not possible? Is the example link I gave misleading?

Here is my code:

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);
  }
})

Thanks for your help!

like image 717
ian Avatar asked Aug 24 '18 19:08

ian


1 Answers

Rookie mistake: I was not escaping the \n in my privateKey string. firebase functions:config:set was converting \n to \\n Fixed code looks like:

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);
  }
});

My actual problem was solved using this advice: Escaping issue with firebase privateKey as a Heroku config variable

like image 147
ian Avatar answered Oct 31 '22 20:10

ian