Skip to content

Instantly share code, notes, and snippets.

@davidovs
Forked from bcnzer/postman-pre-request.js
Last active July 28, 2019 16:07
Show Gist options
  • Save davidovs/df52741c45d95f6476c1cce3ffc7792b to your computer and use it in GitHub Desktop.
Save davidovs/df52741c45d95f6476c1cce3ffc7792b to your computer and use it in GitHub Desktop.
Postman pre-request script to automatically get a bearer token from Keycloak and save it for reuse
const echoPostRequest = {
url: '127.0.0.1:8180/auth/realms/master/protocol/openid-connect/token',
method: 'POST',
header: 'Content-Type:application/x-www-form-urlencoded',
body: {
mode: 'urlencoded',
urlencoded: [
{ key: 'client_id', value: 'admin-cli' },
{ key: 'username', value: 'admin' },
{ key: 'password', value: 'admin' },
{ key: 'grant_type', value: 'password' }
]
}
};
var getToken = true;
if (!pm.environment.get('accessTokenExpiry') ||
!pm.environment.get('currentAccessToken')) {
console.log('Token or expiry date are missing');
} else if (pm.environment.get('accessTokenExpiry') <= (new Date()).getTime() + 5000) {
console.log('Token is expired or is going to expire in 5 seconds');
} else {
getToken = false;
console.log('Token and expiry date are all good');
}
if (getToken === true) {
pm.sendRequest(echoPostRequest, function (err, res) {
console.log(err ? err : res.json());
if (err === null) {
console.log('Saving the token and expiry date');
var responseJson = res.json();
pm.environment.set('currentAccessToken', responseJson.access_token);
var expiryDate = new Date();
expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);
pm.environment.set('accessTokenExpiry', expiryDate.getTime());
}
});
}
@davidovs
Copy link
Author

environment1
environment2
environment3

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