-
-
Save jackphilippi/c685f059d9b15045ee18bd7d47c5453e to your computer and use it in GitHub Desktop.
JWT tokenize - Postman Pre-Request Script
This file contains 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
var header = { | |
alg: "HS256", | |
typ: "JWT" | |
}; | |
var data = injectIAT({ | |
userId: "<userID>", | |
username: "<user>", | |
email: "<email>", | |
displayName: "<displayName>", | |
profileName: "<profileName>", | |
exp: Math.round(Date.now() / 1000) + 300 | |
}); | |
var secret = '<jwtSecret>'; | |
var encodedHeader = base64url(CryptoJS.enc.Utf8.parse(JSON.stringify(header))); | |
var encodedData = base64url(CryptoJS.enc.Utf8.parse(JSON.stringify(data))); | |
var token = `${encodedHeader}.${encodedData}`; | |
var signature = base64url(CryptoJS.HmacSHA256(token, secret)); | |
var signedToken = `${token}.${signature}`; | |
postman.setEnvironmentVariable('jwtToken', signedToken); | |
function base64url(source) { | |
return CryptoJS.enc.Base64 | |
.stringify(source) | |
.replace(/(\+|\/)/g, '-') | |
.replace(/=+$/, ''); | |
} | |
function injectIAT(dataPayload) { | |
return Object.assign( | |
dataPayload, | |
{ iat: Math.floor(Date.now() / 1000) } | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment