Postman pre-request script oder - does not run the requests in the order I expect - postman-pre-request-script

Total postman noob. I have a script (well I don't I am trying to) to do the drudge tasks of authentication and authorization which takes 2 requests:
console.log("START");
var authenticationToken;
// Identity token
var authenticationTokenRequest = {
url: 'xxxx',
method: 'POST',
timeout: 0,
header: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic xxxxx="
},
body: {
mode: 'urlencoded',
urlencoded: [
{key: "grant_type", value: "password"},
{key:"username", value: "xxxxx"},
{key:"password", value: "xxxx"},
]}
};
pm.sendRequest(authenticationTokenRequest, function (err, res) {
**console.log("01 send first request body");**
var responseJson = res.json();
console.log(responseJson);
pm.environment.set('ACCESS_TOKEN', responseJson['access_token']);
authenticationToken = responseJson['access_token'];
});
**console.log("Authentication token local var: " + authenticationToken);
console.log("Authorization token env var: " + pm.environment.get('ACCESS_TOKEN'));**
var authorizationTokenRequest = {
url: "xxxx",
method: "POST",
header: {
"Content-Type": "application/json",
"Authorization": "Bearer " + authenticationToken,
"Accept": "application/xxx+json"
},
body:{
tenantId: "xxx",
deviceId: "xxx"
}
}
pm.sendRequest(authorizationTokenRequest, function (err, res) {
**console.log("02 second request call");**
var responseJson = res.json();
pm.environment.set('ACCESS_TOKEN', responseJson['access_token']);
});
//
When I run this and look at the console, the console messages of the local vars show undefined. The console message for the second request shows in console before the first request. The second request depends on a value from the first.
What am I doing wrong? Thanks

Related

Postman Pre-Request Script AWS Cognito Token Invalid Grant

This has me stumped.
I have a cognito pool with a resource server, one custom scope and one app client (clientid and secret).
I have my (pre-request) script set up in Postman like this
const clientId = pm.environment.get("cognitoClientId");
const clientSecret = pm.environment.get("cognitoClientSecret");
const grantType = "client_credentials";
const tokenUrl = pm.environment.get("cognitoAuthTokenURL");
const postRequest = {
url: tokenUrl,
method: 'POST',
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: {
mode: 'urlencoded',
urlencoded: [
{
key: "grant_type",
value: grantType
},
{
key: "client_id",
value: clientId
},
{
key: "client_secret",
value: clientSecret
},
{
key: "scope",
value: "myResourceServer/myResource.list"
}
]
}
};
pm.sendRequest(
postRequest
,(error, response) => {
console.log("Callback fired");
console.log(error);
console.log(response);
}
);
It fails on the response body with the following error:
{"error":"invalid_grant"}
From the AWS Documentation I get
Refresh token has been revoked
Which makes no sense as I am not requesting a refresh token
What am I doing wrong here, or where should I be looking?

Postman. Getting "JSONError: No data" after sending Cognito token pre-request

let tokenUrl = 'https://my.url/oauth2/token';
let scope = 'pets/read pets/updage petId/read'
let getTokenRequest = {
method: 'POST',
url: tokenUrl,
header: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: 'Basic Base64Encode(client_id:client_secret)'}, // encoded manually beforehand
body: {
mode: 'formdata',
formdata: [
{ key: 'grant_type', value: 'client_credentials' },
{ key: 'scope', value: scope }
]
}
};
pm.sendRequest(getTokenRequest, (err, response) => {
let jsonResponse = response.json(),
newAccessToken = jsonResponse.access_token;
pm.environment.set('access_token', newAccessToken);
pm.variables.set('access_token', newAccessToken);
});
Geeks, help, please!
I have API with Cognito authorization (Client Credentials type). It work's fine in Postman with manually 'Request new Access token'. But I want to retrieve token with pre-request script. I relied on AWS documentation about token endpoint. I have
JSONError: No data, empty input at 1:1
in the console. Do you have any suggestions?
I've encountered the same problem and resolved it by setting grant_type and scope as query string in the url:
let tokenUrl = pm.variables.get("cognito-url")+ "/oauth2/token?grant_type=client_credentials&scope=' + pm.variables.get("cognito-scope");
let auth_code = btoa(pm.variables.get("cognito-client-id") + ":" + pm.variables.get("cognito-client-secret"))
let getTokenRequest = {
method: 'POST',
url: tokenUrl,
header: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + auth_code}
};
pm.sendRequest(getTokenRequest, (err, response) => {
let jsonResponse = response.json(),
newAccessToken = jsonResponse.access_token;
pm.environment.set('access_token', newAccessToken);
pm.variables.set('access_token', newAccessToken);
});

Parsing nested elements from JSON response using a postman test script

I'm using the following Postman test script to check and log the status of a POST.
pm.environment.unset("uuid");
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("uuid", jsonData.id);
var base = pm.request.url
var url = base + '/status?uuid=' + pm.environment.get("uuid");
var account = pm.request.headers.get("account")
var auth = pm.request.headers.get("Authorization")
pm.test("Status code is 200",
setTimeout(function() {
console.log("Sleeping for 3 seconds before next request.");
pm.sendRequest ( {
url: url,
method: 'GET',
header: {
'account': account,
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8',
'Authorization': auth
}
},
function (err, res) {
console.log(res.json().messageSummary);
})
},3000)
);
The script is able to make the call and retrieve the messageSummary from the response:
{
"id": "3c99af22-ea07-4f5d-bfe8-74a6074af71e",
"status": "SUCCESS",
"token": null,
"messageSummary": "[2] Records uploaded, please check errors/warnings and try again.",
"data": [
{
"ErrorCode": "-553",
"ErrorMessage": "Error during retrieving service service_id entered"
}
]
}
I'm wanting to also get the nested ErrorMessage, but so far everything I've tried comes back undefined or throws an error.
I assumed console.log(res.json().data[1].ErrorMessage) would work, but, alas, it does not.
UPDATE: arrays start with [0] not [1]...
pm.environment.unset("uuid");
var jsonData = pm.response.json();
pm.environment.set("uuid", jsonData.id);
var base = pm.request.url
var url = base + '/status?uuid=' + pm.environment.get("uuid");
var account = pm.request.headers.get("account")
var auth = pm.request.headers.get("Authorization")
setTimeout(function() {
console.log("Sleeping for 3 seconds before next request.");
pm.sendRequest ( {
url: url,
method: 'GET',
header: {
'account': account,
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8',
'Authorization': auth
}
},
function (err, res) {
console.log(res.json().messageSummary);
console.log(res.json().data[0].ErrorCode + ': ' + res.json().data[0].ErrorMessage)
})
},3000)
You would need to change the [1] to [0] to fix that reference.

sendRequest does not seem to use Headers values I specify in the Test

I'm using sendRequest function to send a 2nd request as part of the Test for my 1st request. But it seems that sendRequest does not use the Headers I specify in the function. Any ideas why and how to fix it?
Here is part of my Test, that sends 2nd request:
var runHost = pm.environment.get("MyHost");
var runToken = pm.environment.get("Token");
pm.sendRequest({
url: runHost,
method: 'PUT',
headers: {
"Authorization": "Auth "+runToken,
"Accept": "application/json",
"Content-Type": "application/json"
},
body: {
mode: 'raw',
raw: JSON.stringify(jsonData)
}
}, (err, res) => {
console.log(res);
});
Here is what I see as an actual Request Headers sent (what I see in Console):
PUT https://some_url
Request Headers:
Content-Type:"text/plain"
User-Agent:"PostmanRuntime/7.15.2"
Accept:"*/*"
Cache-Control:"no-cache"
Postman-Token:"5e3543c-1ww0-dfc4-bert-92ba9a455667"
Host:"my_host"
Accept-Encoding:"gzip, deflate"
Content-Length:1876
Connection:"keep-alive"
I expect Request Headers to have the following attributes and values:
Authorization:"Auth current_token_value"
Accept:"application/json"
Content-Type:"application/json"
...
The key for the object that contains the Request Headers should be header, like in the example below:
pm.sendRequest({
url: runHost,
method: 'PUT',
*header*: {
"Authorization": "Auth "+runToken,
"Accept": "application/json",
"Content-Type": "application/json"
},
body: {
mode: 'raw',
raw: JSON.stringify(jsonData)
}
}, (err, res) => {
console.log(res);
});

loopback rest connection headers authorization

I'm trying to access the Shopify Orders API in a Loopback application. I have the following data source:
"ShopifyRestDataSource": {
"name": "ShopifyRestDataSource",
"connector": "rest",
"operations": [{
"template": {
"method": "GET",
"url": "https://mystore.myshopify.com/admin",
"headers": {
"accepts": "application/json",
"content-type": "application/json"
}
},
"headers": {
"Authorization": "Basic MzdiOD..."
},
"functions": {
"find": []
}
}]
}
And then I attempt a simple call:
var ds = app.dataSources.ShopifyRestDataSource;
ds.find(function(err, response, context) {
if (err) throw err;
if (response.error) {
next('> response error: ' + response.error.stack);
}
console.log(response);
next();
});
I'm getting the following exception message:
Error: {"errors":"[API] Invalid API key or access token (unrecognized login or wrong password)"}
at callback (/order-api/node_modules/loopback-connector-rest/lib/rest-builder.js:529:21)
The Shopify API authenticates by basic HTTP authentication and I'm sure my request works since the same data works with curl. What am I doing wrong?
I couldn't find the "Loopback way" to do this and I couldn't wait, so I just wrote a simple https Node call. I'll paste this in here but I won't accept it as the answer. I'm still hoping someone will provide the right answer.
let response;
const options = {
hostname: 'mystore.myshopify.com',
port: 443,
path: '/admin/orders.json',
method: 'GET',
auth: `${instance.api_key}:${instance.password}`
};
const req = https.request(options, (res) => {
res.setEncoding('utf8');
let body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
let jsonResponse = JSON.parse(body);
// application logic goes here
response = 'ok';
});
});
req.on('error', (e) => {
response = e.message;
});
req.end();