Created
September 10, 2018 08:34
-
-
Save DannyDainton/1ea5beecf81c0f32e63e94cd7cb6199d to your computer and use it in GitHub Desktop.
Automatically set a JWT if the current one is invalid
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
// This can be placed in the Pre-requests on the collection level. | |
// It will check to see if certain valid variables are present in an environment file. | |
// If these are not present, it be go and get another valid token | |
// The 'AuthData' variable is a Base64 encoded client_id and client_secret | |
// This my need to be tweaked for your needs but the mechanism will work. | |
const moment = require('moment') | |
const getJWT = { | |
url: `${pm.environment.get('tokenBaseURL')}/Auth/connect/token`, | |
method: 'POST', | |
header: { | |
'Content-Type': 'application/x-www-form-urlencoded', | |
'Authorization': `Basic ${pm.environment.get('AuthData')}` | |
}, | |
body: { | |
mode: 'urlencoded', | |
urlencoded: [ | |
{key: 'grant_type', value: 'client_credentials'}, | |
{key: 'scope', value: '<scope details>'} | |
] | |
} | |
} | |
var getToken = true | |
if (!_.has(pm.environment.toObject(), 'AccessTokenExpiry') | |
|| !_.has(pm.environment.toObject(), 'jwt') | |
|| pm.environment.get('AccessTokenExpiry') <= moment().valueOf()) { | |
} else { | |
getToken = false | |
} | |
if (getToken) { | |
pm.sendRequest(getJWT, (err, res) => { | |
if (err === null) { | |
pm.environment.set('jwt', `Bearer ${res.json().access_token}`) | |
var expiryDate = moment().add(res.json().expires_in, 's').valueOf() | |
pm.environment.set('AccessTokenExpiry', expiryDate) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment