Last active
June 5, 2022 09:05
-
-
Save naoki-sawada/75a34565df860bb9996df1b2b92856e8 to your computer and use it in GitHub Desktop.
The pre-request script to automatically renewal the JWT in Postman.
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
function parseJwt (token) { | |
const base64Url = token.split('.')[1]; | |
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); | |
const jsonPayload = decodeURIComponent(atob(base64).split('').map((c) => { | |
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); | |
}).join('')); | |
return JSON.parse(jsonPayload); | |
}; | |
function isValidToken(token) { | |
if (!token) return false; | |
const { exp } = parseJwt(token); | |
if (!exp) return false; | |
return new Date().getTime() < new Date(exp * 1000).getTime(); | |
} | |
function setJwtEnv(envKey, refreshFunc) { | |
if (!envKey || !refreshFunc) return console.error("Argument is required"); | |
const latestToken = pm.environment.get(envKey); | |
if (!isValidToken(latestToken)) { | |
refreshFunc((token) => pm.environment.set(envKey, token)); | |
} | |
} | |
const req = { | |
url: '[your-token-provider-url]', | |
method: 'POST', | |
header: { | |
'Content-Type': 'application/json', | |
}, | |
body: { | |
mode: 'raw', | |
raw: JSON.stringify({ email: '[your-email]', password: '[your-password]' }) | |
}, | |
}; | |
setJwtEnv("token", (setToken) => { | |
pm.sendRequest(req, (error, response) => { | |
if (error) return console.error(error); | |
if (response.code !== 200) return console.error(response); | |
const { id_token } = response.json(); | |
if (id_token) { | |
setToken(id_token); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment