Skip to content

Instantly share code, notes, and snippets.

@thim81
Created June 14, 2021 06:02
Show Gist options
  • Save thim81/a1e218272fbcf934bcbc2d19cab70fef to your computer and use it in GitHub Desktop.
Save thim81/a1e218272fbcf934bcbc2d19cab70fef to your computer and use it in GitHub Desktop.
Auth0 - Outh2 - Postman pre-request script
{
"name": "Auth0-Oauth2",
"values": [
{
"key": "baseUrl",
"value": "https://example.com/api",
"enabled": true
},
{
"key": "oauth_access_token",
"value": "",
"enabled": true
},
{
"key": "oauth_access_token_expires",
"value": "",
"enabled": true
},
{
"key": "oauth_access_token_url",
"value": "https://[enter-your-own].auth0.com/oauth/token",
"enabled": true
},
{
"key": "oauth_grant_type",
"value": "client_credentials",
"enabled": true
},
{
"key": "oauth_client_id",
"value": "",
"enabled": true
},
{
"key": "oauth_client_secret",
"value": "",
"enabled": true
},
{
"key": "oauth_audience",
"value": "",
"enabled": true
}
],
"_postman_variable_scope": "environment",
}
const currentTime = new Date().getTime();
const oauthTokenUrl = pm.environment.get('oauth_access_token_url');
const oauthGrantType = pm.environment.get('oauth_grant_type');
const oauthClientId = pm.environment.get('oauth_client_id');
const oauthClientSecret = pm.environment.get('oauth_client_secret');
const oauthAudience = pm.environment.get('oauth_audience');
const getTokenRequest = {
method: 'POST',
url: oauthTokenUrl,
header: {'Content-Type': 'application/json'},
body: {
mode: 'raw',
raw: JSON.stringify({
'grant_type': oauthGrantType,
'client_id': oauthClientId,
'client_secret': oauthClientSecret,
'audience': oauthAudience
})
}
};
// Fetch new access token, if empty OR if is expired
if (!(pm.environment.get('oauth_access_token')) || (currentTime >= pm.environment.get('oauth_access_token_expires'))) {
pm.sendRequest(getTokenRequest, (err, res) => {
let jsonData = res.json();
pm.environment.set('oauth_access_token', jsonData.access_token);
pm.environment.set('oauth_access_token_expires', new Date().getTime() + jsonData.expires_in);
});
console.log('Oauth access token refreshed & ready to use')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment