Created
September 20, 2018 18:23
-
-
Save harryi3t/dd5c61451206047db70710ff6174c3c1 to your computer and use it in GitHub Desktop.
This gist shows how using the pre-request script in Postman, a new Oauth-2 token can be obtained using the a refresh token
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
/** | |
** Postman as of the date of this writing does not support auto-refreshing of Oauth-2 tokens. | |
** This is an exmaple on how in one can refresh their Oauth-2 tokens just using the pre-request scripts. | |
** Pre-requisites: You need to have a refresh token. You can use the Postman app to get one. | |
**/ | |
// Set all these variables in an environment or at collection level | |
let tokenUrl = pm.variables.get('tokenUrl'), | |
clientId = pm.variables.get('clientId'), | |
clientSecret = pm.variables.get('clientSecret'), | |
refreshToken = pm.variables.get('refreshToken'), | |
requestOptions = { | |
method: 'POST', | |
url: tokenUrl, | |
body: { | |
mode: 'formdata', | |
formdata: [ | |
{ | |
key: 'grant_type', | |
value: 'refresh_token' | |
}, | |
{ | |
key: 'client_id', | |
value: clientId | |
}, | |
{ | |
key: 'client_secret', | |
value: clientSecret | |
}, | |
{ | |
key: 'refresh_token', | |
value: refreshToken | |
} | |
] | |
} | |
}; | |
console.log({ requestOptions }); | |
pm.sendRequest(requestOptions, (err, response) => { | |
let jsonResponse = response.json(), | |
newAccessToken = jsonResponse.access_token; | |
console.log({ err, jsonResponse, newAccessToken }) | |
// If you want to persist the token | |
pm.environment.set('accessToken', newAccessToken); | |
// Or if you just want to use this in the current request and then discard it | |
pm.variables.set('accessToken', newAccessToken); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have a header prefix and "send as basic auth header" in client authentification . so how to fix this script to match my purpose ? Thank you in advance