Skip to content

Instantly share code, notes, and snippets.

@DannyDainton
Created September 10, 2018 08:34
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save DannyDainton/1ea5beecf81c0f32e63e94cd7cb6199d to your computer and use it in GitHub Desktop.
Save DannyDainton/1ea5beecf81c0f32e63e94cd7cb6199d to your computer and use it in GitHub Desktop.
Automatically set a JWT if the current one is invalid
// 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