Skip to content

Instantly share code, notes, and snippets.

@SafeEval
Created March 22, 2023 23:30
Show Gist options
  • Save SafeEval/7acbbdc93d9e0e20b6eb19144ad24f18 to your computer and use it in GitHub Desktop.
Save SafeEval/7acbbdc93d9e0e20b6eb19144ad24f18 to your computer and use it in GitHub Desktop.
Postman pre-request script to dynamically generate a HS256 JWT (invalid signature)
/*
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