Last active
November 30, 2022 08:53
-
-
Save jakeashcraft/f01aa3296b4cc9189a126b86be57686c to your computer and use it in GitHub Desktop.
Postman Pre-request Script used to automatically retrieve a new OAuth2 token when the token is expired
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
pm.expect(pm.globals.has('accessToken')).to.be.true; | |
const sdk = require('postman-collection'); | |
const JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; | |
const currentToken = pm.globals.get('accessToken').replace('Bearer ', ''); | |
const path = pm.environment.get('url') + '/auth/token'; | |
let expired = true; | |
if(currentToken && currentToken.length > 0) { | |
const parsed = jwsDecode(currentToken, null); | |
expired = isTokenExpired(parsed.payload.exp); | |
} | |
if(expired) { | |
const clientId = pm.globals.get('clientId'); | |
const clientSecret = pm.globals.get('clientSecret'); | |
// Create request | |
const tokenRequest = new sdk.Request({ | |
url: path, | |
method: 'GET', | |
header: { | |
'content-type': 'application/json', | |
'lyve-client-id': clientId, | |
'lyve-client-secret': clientSecret | |
} | |
}); | |
pm.sendRequest(tokenRequest, function(err, response) { | |
if(err) { | |
console.log(err); | |
} | |
const json = response.json(); | |
pm.expect(json).to.an('object'); | |
pm.test('response json has needed properties', function() { | |
pm.expect(json).to.have.own.property('access_token'); | |
pm.expect(json).to.have.own.property('expires_in'); | |
pm.expect(json).to.have.own.property('token_type'); | |
const accessToken = json.access_token; | |
const tokenType = json.token_type; | |
const bearer = tokenType + ' ' + accessToken; | |
//console.log(`Bearer Value: ${bearer}`); | |
pm.globals.set('accessToken', bearer); | |
}); | |
}); | |
} else { | |
console.log('Token is still valid'); | |
} | |
function padString(input) { | |
let segmentLength = 4; | |
let stringLength = input.length; | |
let diff = stringLength % segmentLength; | |
if (!diff) { | |
return input; | |
} | |
let position = stringLength; | |
let padLength = segmentLength - diff; | |
let paddedStringLength = stringLength + padLength; | |
let buffer = new Buffer(paddedStringLength); | |
buffer.write(input); | |
while (padLength--) { | |
buffer.write("=", position++); | |
} | |
return buffer.toString(); | |
} | |
function decode(base64url, encoding = "utf8") { | |
return new Buffer(toBase64(base64url), "base64").toString(encoding); | |
} | |
function toBase64(base64url) { | |
base64url = base64url.toString(); | |
return padString(base64url) | |
.replace(/\-/g, "+") | |
.replace(/_/g, "/"); | |
} | |
function isObject(thing) { | |
return Object.prototype.toString.call(thing) === '[object Object]'; | |
} | |
function safeJsonParse(thing) { | |
if (isObject(thing)) | |
return thing; | |
try { return JSON.parse(thing); } catch (e) { return undefined; } | |
} | |
function headerFromJWS(jwsSig) { | |
var encodedHeader = jwsSig.split('.', 1)[0]; | |
return safeJsonParse(decode(encodedHeader, 'binary')); | |
} | |
function isValidJws(string) { | |
return JWS_REGEX.test(string) && !!headerFromJWS(string); | |
} | |
function payloadFromJWS(jwsSig, encoding) { | |
encoding = encoding || 'utf8'; | |
var payload = jwsSig.split('.')[1]; | |
return decode(payload, encoding); | |
} | |
function signatureFromJWS(jwsSig) { | |
return jwsSig.split('.')[2]; | |
} | |
function jwsDecode(jwsSig, opts) { | |
opts = opts || {}; | |
if (!isValidJws(jwsSig)) | |
return null; | |
var header = headerFromJWS(jwsSig); | |
if (!header) | |
return null; | |
var payload = payloadFromJWS(jwsSig); | |
if (header.typ === 'JWT' || opts.json) | |
payload = JSON.parse(payload, opts.encoding); | |
return { | |
header: header, | |
payload: payload, | |
signature: signatureFromJWS(jwsSig) | |
}; | |
} | |
function isTokenExpired(exp) { | |
try { | |
return ((Date.now() / 1000) > exp); | |
} catch (error) { | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment