-
-
Save corbanb/db03150abbe899285d6a86cc480f674d to your computer and use it in GitHub Desktop.
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) + 257; | |
data.iat = iat; | |
return data; | |
} | |
var header = { | |
"typ": "JWT", | |
"alg": "HS256" | |
}; | |
var data = { | |
"fname": "name", | |
"lname": "name", | |
"email": "[email protected]", | |
"password": "abc123$" | |
}; | |
data = addIAT(data); | |
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); | |
// build token | |
var token = encodedHeader + "." + encodedData; | |
// sign token | |
var signature = CryptoJS.HmacSHA256(token, secret); | |
signature = base64url(signature); | |
var signedToken = token + "." + signature; | |
postman.setEnvironmentVariable("payload", signedToken); |
reference this:
https://www.postman.com/postman/workspace/postman-team-collections/request/8140651-fa914e7e-362a-4698-8a5a-0c81dfebf5f9?tab=scripts
`var navigator = {};
var window = {};
eval(pm.environment.get("jsrsasign-js"));
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) }
);
console.log(Private Key: ${ privateKey }
);
// let jws = new KJUR.jws.JWS();
var jwt = KJUR.jws.JWS.sign(null, header, claimSet, privateKey);
console.log(jwt);
pm.environment.set('jwt', jwt);`
In my case changed secret to base64 worked perfectly. Those who are facing problem can try this out