-
-
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
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
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()); | |
} | |
}); | |
} |
Author
davidovs
commented
Jul 28, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment