Postman Pre-Request Script to create JWT for Google Service Account

戏子无情 提交于 2019-12-25 01:37:57

问题


I am trying to create a JWT to get an access token for a Google Service Account to use in a Postman Pre-Request script.

But I keep getting this error in the Postman Console:

Error:

And in the Postman Response window I get:

There was an error in evaluating the Pre-request Script:  undefined: undefined

I localized the error to be failing here:

var jwt = KJUR.jws.JWS.sign(null, header, claimSet, privateKey);

I'm importing it by using a request to http://kjur.github.io/jsrsasign/jsrsasign-latest-all-min.js and saving it to an environment variable called jsrsasign then rehydrating it below with eval.

Pre-Request Script:

var navigator = {};
var window = {};
eval(pm.environment.get("jsrsasign"));

var scope = pm.environment.get('scope');
var iss = pm.environment.get('iss');
var privateKey = pm.environment.get('privateKey');

const header = {"alg" : "RS256", "typ" : "JWT"};

const claimSet =
{
  "iss": iss,
  "scope": scope,
  "aud":"https://oauth2.googleapis.com/token",
  "exp":KJUR.jws.IntDate.get("now + 1hour").toString(),
  "iat": KJUR.jws.IntDate.get("now").toString()
}

console.log(`header: ${ JSON.stringify(header)}`);
console.log(`claim set: ${ JSON.stringify(claimSet) }`);

var jwt = KJUR.jws.JWS.sign(null, header, claimSet, privateKey);

pm.environment.set('jwt', jwt);

Similar issue to this guy's comment on Medium: https://medium.com/@jkohne/hi-klaasjan-tukker-im-trying-to-get-the-library-import-and-eval-to-work-for-jsrsasign-c0c457ddd23f


回答1:


I was able to solve this.

My private key had escaped white space characters in it (\n,\t)

I opened up google chrome dev tools and just saved it to a variable with template literals and console logged it out to get a properly formatted key.

Another option may just to do that in Postman as well.

After that, it worked.

Published Collection: https://documenter.getpostman.com/view/8140651/SWECYFyf?version=latest



来源:https://stackoverflow.com/questions/59383521/postman-pre-request-script-to-create-jwt-for-google-service-account

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!