I have a NuxtJS (v2.15.8) app that needs to consume an API on GCP App Engine (NodeJS) protected by IAP. I'm trying to get an access token for the Service Account I've created as described here: https://cloud.google.com/iap/docs/authentication-howto
I've searched a lot but I can't find on Google nobody with the same or similar need.
After several attempts with different methods, now I'm trying to sign a JWT in my code in order to get the access token from the API. To do this I'm using functions from cryptojs lybrary to create the signature, but I have a problem with the sign() function. It gives me this error:
TypeError: Cannot read properties of null (reading '2') at module.exports (fixProc.js?4dd0:14:1) at parseKeys (index.js?2aee:19:1) at sign (sign.js?6fe7:11:1) at Sign.signMethod [as sign] (index.js?b692:42:1) at _callee2$ (auth.js?889e:78:1) at tryCatch (runtime.js?96cf:63:1) at Generator.invoke [as _invoke] (runtime.js?96cf:294:1) at Generator.eval [as next] (runtime.js?96cf:119:1) at asyncGeneratorStep (asyncToGenerator.js?1da1:3:1) at _next (asyncToGenerator.js?1da1:25:1)
Here's the code I'm using
const qs = require('qs');
const crypto = require('crypto');
const private_key_id=options.private_key_id
const client_email=options.client_email
const private_key=options.private_key
const issued_at=Math.round( new Date()/1000);
const expires_at=issued_at 3600
const header="{'alg':'RS256','typ':'JWT','kid':'" private_key_id "'}"
const header_base64=Buffer.from(header).toString('base64')
const body="{'iss':'" client_email "','aud':'" oauth_token_uri "','exp':" expires_at ",'iat':" issued_at ",'sub':" client_email ",'target_audience':'" iap_client_id "'}"
const body_base64=Buffer.from(body).toString('base64')
const sign = crypto.createSign('sha256');
sign.write(Buffer.from(`${header_base64}.${body_base64}`));
sign.end();
const signature_base64=sign.sign(private_key,'base64');
const assertion=Buffer.from(`${header_base64}.${body_base64}.${signature_base64}`)
axios({
method: 'post',
url: 'https://www.googleapis.com/oauth2/v4/token',
data: qs.stringify({
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: assertion
}),
headers: {
'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
}
}).then(function (response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});
All the variables used are taken from the service account credentials JSON file and set as env variables in my app.
CodePudding user response:
I solved using
const sign = crypto.createSign('RSA-SHA256');
instead of
const sign = crypto.createSign('sha256');