Last active
July 22, 2024 13:12
-
-
Save corbanb/db03150abbe899285d6a86cc480f674d to your computer and use it in GitHub Desktop.
JWT tokenize - Postman Pre-Request Script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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);`