在邮递员预先请求脚本中生成RSA JWT

时间:2019-10-09 10:37:39

标签: google-api postman google-oauth

我具有以下预请求脚本,用于尝试为Google Api生成JWT-Google使用RS256加密,这是我认为遇到的问题-CryptoJS似乎仅支持HmacSHA256-任何建议会有所帮助:

这是我来自邮递员的请求前脚本:

function base64url(source) {
    // Encode in classical base64
    encodedSource = CryptoJS.enc.Base64.stringify(source);

    // Remove padding equal characters
    encodedSource = encodedSource.replace(/=+$/, '');

    // Replace characters according to base64url specifications
    encodedSource = encodedSource.replace(/\+/g, '-');
    encodedSource = encodedSource.replace(/\//g, '_');

    return encodedSource;
}

function addIAT(request) {
    var iat = Math.floor(Date.now() / 1000) - 100;
    data.iat = iat;
    return data;
}

function addEXP(request) {
    var exp = Math.floor(Date.now() / 1000) + 3300;
    data.exp = exp;
    return data;
}


var header = {
    "alg": "RS256",
    "typ": "JWT",
    "kid": "xxx"
};

var data = {
     "iss": "xxx@iam.gserviceaccount.com",
     "aud": "https://oauth2.googleapis.com/token",
     "scope": "https://www.googleapis.com/auth/cloud-platform"

};

data = addIAT(data);
data = addEXP(data);

var privateKEY = "-----BEGIN PRIVATE KEY-----xxxxxxxxxxxxxxxLcGGNkna2Y3URoT0vDNneqzaasmJk4JZ97BcFLOulTihA49z8zmQKBgQDKX9AWS88cnfyiXSxtRNUFYvN4SzMDTJ1o59Gm6Sk77t7Ylfm+8PKA00SQeN7FuU/cbU4PkbAyzcp7eAGE3KXoLC/pWQ14srWGAsQkti1PmBo400ajRQReJPs3XxIl3yl4swlRgn+w9x6xy3CRnWrZRQSxRrtdDkBJcp7Lml+4mwKBgQCCeiTsktlMTOy9LqxOUMh6Lt7Z5jceNSwusW8Z4YVsewiSsRezufLBRcTywifgPOyUTP3S7etEfW2CKF0smpM0drfxd/3Ic7oKr7ESY5zwNcV7Q3NUGxaqGy8yoxEhKkLsYkOzYUdyNyfJd5Sh8yq7ICrX7/UGkVLOi44VrdaluQKBgC3kmH3V5zvoH/h6BK8q4tv72pa3BvSClVfK6mJdkbpDq0mWiTJh1bydLHlOz8YrBg9IwmEJetmqjXZ+emm01/LUwnC6fzGV5VBkpDJnFdNs/NVSJDy2VA09ebLO3oC0IOV8RGq1m1t4Tv+m0PpUpnxrCGtjTO4HY1DEq3okofxtAoGABjq4QegVIlImU5LSAEKgnUiwA1CHGW3+ZzfCczAv2VRfk/DSlYLmsxLRIfjsCVEo79NiVGyIsKmt5TJRxVLXp++ydKCEN/YRrjqEFgHNoH0rDCuV/IKAeN17/TYKphuebSX6mVsfo7GXI1kSoGJkDDnPKR4peiIF/YC9BTqQgIs=-----END PRIVATE KEY-----"

var secret = 'myjwtsecret';

// encode header
var stringifiedHeader = CryptoJS.enc.Utf8.parse(JSON.stringify(header));
var encodedHeader = base64url(stringifiedHeader);

// encode data
var stringifiedData = CryptoJS.enc.Utf8.parse(JSON.stringify(data));
var encodedData = base64url(stringifiedData);

//encode privatekey
//var stringifiedPrivatekey = CryptoJS.enc.Utf8.parse(JSON.stringify(privateKEY));
//var encodedPrivatekey = base64url(stringifiedPrivatekey);

// build token
var token = encodedHeader + "." + encodedData

// sign token
//var signature = CryptoJS.HmacSHA256(token, secret);
//signature = base64url(signature);
var signature = CryptoJS.RS256(token , privateKEY);
signedToken = base64url(signature);

var jwt = token + "." + signedToken


postman.setEnvironmentVariable("payload", jwt);

1 个答案:

答案 0 :(得分:0)

我在项目中几次发现了这个问题,所以我决定创建一个简单的方法来实现这一目标,在这里https://joolfe.github.io/postman-util-lib/,我发布了一个“库”以方便地进行加密操作,例如generate jwt,PKCE挑战...邮递员的“预请求”和“测试”脚本中,有任何疑问,请联系我。

最好的问候。