Last active
January 7, 2022 02:06
-
-
Save nicksherron/ca2320ef498e348b116c3887548c15a4 to your computer and use it in GitHub Desktop.
pre request script to update postman with new keycloak token if its expired
This file contains hidden or 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
| // refresh token if it's expired | |
| var client_id = pm.collectionVariables.get("client_id") | |
| var client_secret = pm.collectionVariables.get("client_secret") | |
| const postRequest = { | |
| url: pm.collectionVariables.get("sandbox_auth_url") + "protocol/openid-connect/token", | |
| method: 'POST', | |
| header: 'Content-Type:application/x-www-form-urlencoded', | |
| body:{ | |
| mode: 'raw', | |
| raw: `grant_type=client_credentials&client_id=${client_id}&client_secret=${client_secret}` | |
| } | |
| } | |
| var getToken = true; | |
| if (!pm.environment.get('accessTokenExpiry') || | |
| !pm.environment.get('token')) { | |
| console.log('Token or expiry date are missing') | |
| } else if (pm.environment.get('accessTokenExpiry') <= (new Date()).getTime()) { | |
| console.log('Token is expired') | |
| } else { | |
| getToken = false; | |
| console.log('Token and expiry date are all good'); | |
| } | |
| if (getToken === true) { | |
| pm.sendRequest(postRequest, (error, response) => { | |
| console.log(error ? error : response.json()) | |
| pm.environment.set('token', response.json().access_token) | |
| var expiryDate = new Date(); | |
| expiryDate.setSeconds(expiryDate.getSeconds() + response.json().expires_in); | |
| pm.environment.set('accessTokenExpiry', expiryDate.getTime()); | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment