Last active
June 2, 2020 13:17
-
-
Save GabrielGil/e92635fad9368d65ca03e6277a20355e to your computer and use it in GitHub Desktop.
Refresh a JWT on Postman without having to input the token constantly on the header.
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
// Data location | |
const ENV_EMAIL = 'email'; | |
const ENV_HOST = 'hostname'; | |
const ENV_PASS = 'password'; | |
const ENV_TOKEN = 'idToken'; | |
/** | |
* Determine if a token is expired already | |
*/ | |
function isTokenExpired(idToken) { | |
if(!idToken) return null; | |
// Split token parts | |
let encoded = idToken.split('.')[1]; | |
// Decode payload | |
let data = atob(encoded); | |
// Parse JSON | |
let payload = JSON.parse(data); | |
// Compare expiration date | |
let expirationDate = new Date(payload.exp*1000); | |
let now = new Date(); | |
return expirationDate <= now; | |
} | |
// Check whether there is a token on the environment and it is expired | |
if(pm.environment.has(ENV_TOKEN) && isTokenExpired(pm.environment.get(ENV_TOKEN))) { | |
// Retrieve an auth token from the login endpoint | |
if( | |
pm.environment.has(ENV_EMAIL) && | |
pm.environment.has(ENV_PASS) && | |
pm.environment.has(ENV_HOST) | |
) { | |
const authLoginRequest = { | |
url: pm.environment.get(ENV_HOST)+'/auth/login', | |
method: 'POST', | |
header: [ | |
'accept:application/x.api.v2+json', | |
'content-type:application/json', | |
], | |
body: { | |
mode: 'raw', | |
raw: JSON.stringify({ | |
email: pm.environment.get(ENV_EMAIL), | |
password: pm.environment.get(ENV_PASS) | |
}) | |
} | |
}; | |
// Save the token on the environment for future requests | |
pm.sendRequest(authLoginRequest, function(err, response) { | |
let token = response.json().data.token; | |
pm.environment.set(ENV_TOKEN, token); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment