Created
March 22, 2023 23:30
-
-
Save SafeEval/7acbbdc93d9e0e20b6eb19144ad24f18 to your computer and use it in GitHub Desktop.
Postman pre-request script to dynamically generate a HS256 JWT (invalid signature)
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
/* | |
References: | |
- https://stackoverflow.com/questions/67432096/generating-jwt-tokens | |
- https://faun.pub/auto-generating-jwt-tokens-with-postman-2b6dd4e29897 | |
*/ | |
const duration = 3600 // 1 hour | |
const issuedAtOffest = 5 | |
const HMACSHA256 = (stringToSign, secret) => "not_implemented" | |
// Dynamic values.- issuedAtOffest | |
const currentTime = +new Date(); // Current time in milliseconds. | |
const issuedAtTimeSeconds = Math.round(currentTime/1000) - issuedAtOffest; | |
const expirationTimeSeconds = Math.round(currentTime/1000) + duration - issuedAtOffest; | |
// Define. | |
const header = { | |
"alg": "HS256", | |
"typ": "JWT" | |
} | |
const claims = { | |
"sub": "1234567890", | |
"name": "John Doe", | |
"iat": issuedAtTimeSeconds, | |
"exp": expirationTimeSeconds | |
} | |
// Encode and assemble. | |
const encodedHeaders = btoa(JSON.stringify(header)) | |
const encodedPlayload = btoa(JSON.stringify(claims)) | |
// "Sign" (signature will be invalid) | |
const signature = HMACSHA256(`${encodedHeaders}.${encodedPlayload}`, "foobar") | |
const encodedSignature = btoa(signature) | |
// Assemble. | |
const jwt = `${encodedHeaders}.${encodedPlayload}.${encodedSignature}`.replace("=", "") | |
// Results. | |
console.log(currentTime, {jwt}) | |
pm.environment.set('jwt', jwt); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment