我正在尝试通过构建描述的 JWS/JWT 内容在 Google Apps 脚本中执行 Google oAuth2 方法。
现在,我可以从云端硬盘或其他来源读取 key 文件,但我应该如何使用此文件对其进行签名?是否有任何方法或 JavaSCript 片段可以做到这一点?
function Auth20(user) {
var header = Utilities.base64Encode(JSON.stringify( {"alg":"RS256","typ":"JWT"} ) );
var claimdata = {
"iss":"1002979611916q0iraclc6q33xxxxxxxx@developer.gserviceaccount.com",
"prn": user,
"scope":"https://www.googleapis.com/auth/plus.circles.read",
"aud":"https://accounts.google.com/o/oauth2/token",
"exp":new Date().getTime()/1000,
"iat":(new Date().getTime()/1000)+3600
}
var claim = Utilities.base64Encode(JSON.stringify( claimdata ))
var jws = header+"."+claim;
var jwsbytes = [];
for (var i = 0; i < jws.length; ++i)
{
jwsbytes.push(jws.charCodeAt(i));
}
var key = DriveApp.getFileById("0B_5HSTQXtXmsU29fTE5xNWhvOVE").getBlob()
最佳答案
像下面这样的函数应该可以解决问题。需要注意两点:
1) 私钥需要采用私钥格式,而不是 RSA 私钥格式。如果您的 key 是后者,则需要 openssl,它允许您为存储在 private.pem
文件中的 key 运行以下命令。还要注意在 GAS 中使用时带有显式 \n
的字符串格式:
openssl pkcs8 -topk8 -inform pem -in private.pem -outform pem -nocrypt -out newPrivate.pem
2) Utilities.base64EncodeWebSafe()
可能会以 =
符号的形式返回终端填充。这些需要删除,因此我包含了 .replace(/=+$/, '')
综合起来:
function Auth20(user) {
var privateKey = "-----BEGIN PRIVATE KEY-----\n{privatekeyhere}\n-----END PRIVATE KEY-----\n"
var header = {
alg: 'RS256',
typ: 'JWT'
};
var now = new Date();
var claimSet = {
iss: {your_iss},
prn: user,
scope: "https://www.googleapis.com/auth/plus.circles.read",
aud:"https://accounts.google.com/o/oauth2/token",
exp: (now.getTime() / 1000) + 3000,
iat: now.getTime() / 1000
};
var toSign = Utilities.base64EncodeWebSafe(JSON.stringify(header)) + '.' + Utilities.base64EncodeWebSafe(JSON.stringify(claimSet));
toSign = toSign.replace(/=+$/, '');
var signatureBytes = Utilities.computeRsaSha256Signature(toSign, privateKey);
var signature = Utilities.base64EncodeWebSafe(signatureBytes);
signature = signature.replace(/=+$/, '');
return toSign + '.' + signature;
};
关于javascript - 使用 Google Apps 脚本执行 SHA256withRSA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21439666/