问题描述
我正在尝试创建一个JWT,以获取Google服务帐户的访问令牌,以用于邮递员的预请求脚本中.
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.
但是我在Postman控制台中仍然收到此错误:
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);
我通过使用对http://kjur.github.io/jsrsasign/jsrsasign-latest-all-min.js
的请求将其导入,并将其保存到名为jsrsasign
的环境变量中,然后在下面用eval将其补水.
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.
预请求脚本:
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);
此人对Medium的评论与此类似: https://medium.com/@jkohne/hi-klaasjan-tukker-im-trying-to-get-the-library-import-and-eval-to-work-for-jsrsasign- c0c457ddd23f
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
推荐答案
我能够解决此问题.
我的私钥中的转义字符(\n
,\t
)
My private key had escaped white space characters in it (\n
,\t
)
我打开了google chrome开发工具,然后将其保存到带有模板文字的变量中,然后控制台将其注销以获取格式正确的密钥.
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.
另一个选项可能也可以在Postman中做到这一点.
Another option may just to do that in Postman as well.
此后,它起作用了.
已发布的收藏集: https://documenter.getpostman.com/view/8140651/SWECYFyf?version=最新
这篇关于邮递员预请求脚本为Google服务帐户创建JWT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!