Skip to content

Instantly share code, notes, and snippets.

@jschuur
Last active July 14, 2021 10:38
Show Gist options
  • Save jschuur/0707fab5d4674f0754bac9a5ef19037c to your computer and use it in GitHub Desktop.
Save jschuur/0707fab5d4674f0754bac9a5ef19037c to your computer and use it in GitHub Desktop.
Automatically update expired OAuth access tokens when making Postman API requests
// How to automatically refresh a bearer token in Postman API client requests when it's expired.
// This pre-request script (https://learning.postman.com/docs/writing-scripts/pre-request-scripts/)
// checks if an access token exists and is not expired, otherwise it will request a new one. It then
// saves it with the expiration date, so it can check against that before the next request.
// Add this at the collection level to apply to all API requests within that collection. Set your
// collection authorization to 'Bearer Token' and the token to '{{access_token}}' and use 'inherit
// auth from parent' for the individual request authorization setting.
// The Twitch API is used here, but the Oauth implementation is standard enough that it can easily
// be adapted for other APIs.
// The Postman environment should also define Twitch API app credentials as TWITCH_CLIENT_ID and
// TWITCH_CLIENT_SECRET.
// Initial code via Benney Au: https://www.pluralsight.com/guides/set-up-postman-and-automatically-add-bearer-tokens
var access_token_expires_on = pm.environment.get("access_token_expires_on");
const current_access_token = pm.environment.get("access_token");
var now = (new Date()).toISOString();
// Get a new access token if there's none, or if it's expired
if(!current_access_token || !access_token_expires_on || access_token_expires_on > now) {
console.log('Refreshing Twitch API access token');
const OAUTH_TOKEN_URL = 'https://id.twitch.tv/oauth2/token';
// Twitch app credentials from https://dev.twitch.tv/console/apps
const client_id = pm.environment.get("TWITCH_CLIENT_ID");
const client_secret = pm.environment.get("TWITCH_CLIENT_SECRET");
const getTokenRequest = {
method: 'POST',
url: OAUTH_TOKEN_URL,
body: {
mode: 'formdata',
formdata: [
{ key: 'grant_type', value: 'client_credentials' },
{ key: 'client_id', value: client_id },
{ key: 'client_secret', value: client_secret }
]
}
};
// Get an updated access token
pm.sendRequest(getTokenRequest, (err, response) => {
const body = response.json();
// expires_in is the time in milliseconds from now when the token will expire
const { access_token, expires_in } = body;
// Save the new token's expiration time
now = new Date();
access_token_expires_on = new Date(now.getTime() + expires_in * 1000);
pm.environment.set('access_token_expires_on', access_token_expires_on)
pm.environment.set('access_token', access_token);
});
}
// Optionally, add the client ID to all headers, as needed per Twitch Helix API
// (https://dev.twitch.tv/docs/authentication/)
pm.request.headers.add({ key: "Client-Id", value: pm.environment.get("TWITCH_CLIENT_ID")});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment