Created
February 26, 2020 15:04
-
-
Save victoroliveirab/8abef6671eaaebdfe57bc4a299c8a209 to your computer and use it in GitHub Desktop.
Postman Pre-Request Script
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
// Adapted from: | |
// https://www.nicolaswidart.com/blog/automatically-set-authentication-tokens-in-postman-requests | |
var requiredAuthPath = pm.environment.get('requiredAuthPath'); | |
var authServicePath = pm.environment.get('authServicePath'); | |
var gatewayBaseUrl = pm.environment.get('gatewayBaseUrl'); | |
var username = pm.environment.get('username'); | |
var password = pm.environment.get('password'); | |
var sdk = require('postman-collection'); | |
var isValidTokenRequest = new sdk.Request({ | |
url: gatewayBaseUrl + requiredAuthPath, // Use an endpoint that requires being authenticated | |
method: 'GET', | |
header: [ | |
new sdk.Header({ | |
key: 'content-type', | |
value: 'application/json', | |
}), | |
new sdk.Header({ | |
key: 'acccept', | |
value: 'application/json', | |
}), | |
new sdk.Header({ | |
key: 'Authorization', | |
value: 'Bearer ' + pm.globals.get("jwttoken"), | |
}), | |
] | |
}); | |
pm.sendRequest(isValidTokenRequest, function (err, response) { | |
console.log(isValidTokenRequest); | |
if (response.code === 401 || response.code === 403) { | |
refreshToken(); | |
} | |
}); | |
function refreshToken() { | |
var tokenRequest = new sdk.Request({ | |
url: gatewayBaseUrl + authServicePath, | |
method: 'POST', | |
header: [ | |
new sdk.Header({ | |
key: 'content-type', | |
value: 'application/json' | |
}), | |
new sdk.Header({ | |
key: 'acccept', | |
value: 'application/json' | |
}), | |
], | |
body: { | |
mode: 'raw', | |
raw: JSON.stringify({ | |
username: username, | |
password: password | |
}) | |
} | |
}); | |
pm.sendRequest(tokenRequest, function (err, response) { | |
if (err) { | |
throw err; | |
} | |
if (response.code !== 200) { | |
throw new Error('Could not log in.'); | |
} | |
// Response: http://www.postmanlabs.com/postman-collection/HeaderList.html | |
pm.globals.set("jwttoken", response.headers.get("Authorization").split(' ')[1]); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment