I have an application that goes through the login page with username and password credentials and then has a get request with /dev/users/current which has the bearer token I would like to refresh when it’s old. I am getting a 401 error on the current page, a 200 status on the login page and this error (New token has been set: undefined).
I also set environmental variables for authSericeUrl and gatewayUrl as well as the credentials
Does anyone know the problem
var authServiceUrl = pm.environment.get('authServiceUrl');
var gatewayBaseUrl = pm.environment.get('gatewayUrl');
var username = pm.environment.get('username');
var password = pm.environment.get('password');
var sdk = require('postman-collection');
var isValidTokenRequest = new sdk.Request({
url: gatewayBaseUrl + "/dev/users/current", // 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.environment.get("jwtToken"),
}),
]
});
pm.sendRequest(isValidTokenRequest, function (err, response) {
if (response.code === 401) {
refreshToken();
}
});
function refreshToken() {
var tokenRequest = new sdk.Request({
url: authServiceUrl,
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.');
}
pm.environment.set("jwtToken", response.json().token);
console.log(`New token has been set: ${response.json().token}`);
});
}