Skip to content

Instantly share code, notes, and snippets.

@harryi3t
Created September 20, 2018 18:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save harryi3t/dd5c61451206047db70710ff6174c3c1 to your computer and use it in GitHub Desktop.
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
/**
** 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);
});
@faycalslm
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment