Last active
November 9, 2023 08:49
-
-
Save Glideh/0f24b8973bb7d79ae8124fa160966df1 to your computer and use it in GitHub Desktop.
Postman pre-request script to get a JWT if needed
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
/** Checks if the JWT is present and not expired | |
The token is expected to be found in `token` environment variable | |
*/ | |
function isValidToken() { | |
const token = pm.environment.get("token"); | |
if (!token) { | |
console.log("Token is missing"); | |
return false; | |
} | |
// Payload is retrieved after JSON parsing the base64 decoded `atob()` 2nd part of the JWT `[1]` | |
// (1st is the header, 3rd is the signature) | |
const payload = JSON.parse(atob(token.split('.')[1])); | |
// Expiration timestamp (in seconds) is located in the `exp` key | |
const millisecBeforeExpiration = (payload.exp * 1000) - (new Date()).getTime(); | |
if (millisecBeforeExpiration <= 0) { | |
console.log("Token is expired"); | |
return false; | |
} | |
console.log("Token is valid", `will expire in ${millisecBeforeExpiration / 1000} seconds`); | |
return true; | |
} | |
/** Gets a new JWT | |
This can be entirely custom authentication. | |
Here we rely on `user`/`pass` environment variables. | |
`host` also needs to be set and feel free to use another route instead of /give-me-a-jwt :) | |
*/ | |
function login() { | |
const body = JSON.stringify({ | |
"user": pm.collectionVariables.get("user"), | |
"pass": pm.collectionVariables.get("pass") | |
}); | |
const request = { | |
url: pm.collectionVariables.get("host") + "/give-me-a-jwt", | |
method: "POST", | |
header: { | |
"Content-Type": "application/json", | |
"Accept": "application/json", | |
}, | |
body, | |
}; | |
pm.sendRequest(request, (err, res) => { | |
if (res.code !== 200) throw new Error(res.status); | |
console.log("Token refreshed"); | |
pm.environment.set("token", res.json().token); | |
}); | |
} | |
if (!isValidToken()) login(); | |
// Of course don't forget to use your brand new token in your Bearer Token authentication type |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment