Postman is not adding headers programmatically - postman

Using Postman 5.5.0 on Ubuntu 16.04. I have the following pre-request script defined for my entire collection. My goal is to set a header on each request at the collection level without having to add it manually.
console.log('adding "Authorization: Token {{apiToken}}" header to current request');
pm.request.headers.add({
key: 'Authorization',
value: 'Token {{apiToken}}'
});
console.log(pm.request.headers);
I also tried setting the header value directly with value: 'Token '+pm.environment.get('apiToken').
Neither approach actually adds it to the requests. The pm.request.headers is reporting that it's there, but come show time, it sure ain't. Here is the console output:
I also tried adding disabled: false to the object passed to add, based on what's there if I add the header to a single request manually.
What's going on?

If you're trying to use the {{...}} syntax in the Pre-request Script or Tests tab it's not going to set the environment variable value for you, as this can only be used in the URL, Headers and the Request body.
The way that you had it in your code, would always just be setting the Authorization key as the string - 'Token {{apiToken}}'.
A completely horrible way of getting the value would be this:
pm.request.headers.add({
key: 'Authorization',
value: `Token ${pm.environment.get('apiToken')}`
});
But again that's not going to set the header at the collection level.
You can add it as a global variable at the collection level in a pre-request script - This can then be added to each request.

Related

Postman - access URLs from collection in a scrip

I want to chain some requests in order to always have an up to date variable containing a JWT for access.
Now i am new to scripting in Postman, i figured this can be done in pre-request scripts. There i can access (global / environment) variables, but i wonder can i also access a saved request from a collection in a script?
The saved request has body and header set, partially with environment vars.
Environment and collection variables can be accessed like this, i know:
pm.environment.get('some_var')
pm.collectionVariables.get('name')
This is the snippet provided by Postman
pm.sendRequest("https://postman-echo.com/get", function (err, response) {
console.log(response.json());
});
Is there a way so i can do something like
pm.collection.url.get('obtain_jwt')
if i have a request called 'obtain_jwt' in a collection?
Or do i have to store the URL as a variable as well and again fill body and header in the script? (which i want to avoid)
I don't think it's supported in Postman the way that you're thinking, it's a feature that's been an ask for a long time:
https://github.com/postmanlabs/postman-app-support/issues/4193
You'll need to fully construct the request in the pre-request script or you might be able to leverage setNextRequest

GraphQL playground - sending Cookie as Http Header "disappears"

I'm testing some implementations in the GraphQL Playground, in which I want to send a specific cookie, so that I can fetch it in my resolver. I'm using the built in Http Headers pane in the playground:
However, when I add headers named either Cookie or cookie, it doesn't show up when I try to console.log it in my resolver. All other custom Http Headers show up with no issues.
As seen in the above screenshoot the testheader appears, but the cookie header doesn't. I'm using cookieParser, which might to blame for the cookie header disappearing, however I'm not sure. Here is a screenshot of my console.log section:
And when I try to console.log the req.cookies, I get nothing, which is to be one of the benefits of using the cookieParser.
My ApolloServer implementation is as follows:
const server = new ApolloServer({
typeDefs: schema
resolvers,
dataSources: () => ({
// ...
}),
context: ({req, res}) => ({
models,
session: req.session,
req,
res
}),
// ... and the rest is not important
});
Creating a "custom" cookie header could do the trick, such as somecookie: <key>=<value>, but I don't think that's the best practice, and would prefer to avoid that. I'm hoping someone out there got an idea why my cookie header doesn't appear, or what I can do for it to appear?
After extensive searching, documentation reading and etc. I figured out how I could make this work.
In the GraphQL playground settings (gear icon), located in the upper right corner of the window:
I changed the line "request.credentials" to "include" and SAVING the settings in the UI. Read more here.
This line is taken directly from the documentation:
'request.credentials': 'omit', // possible values: 'omit', 'include', 'same-origin'
Then following that, I opened the developer tools window (usually F12), went to the tab Application. In here I simply added a cookie as seen in the screenshot. That cookie was sent together with my request.

Value of an environment variable is reset to null in Postman

I have a login request that returns a token that gets saved to environment variables via the following script added in Postman - Tests tab:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("token_abc", jsonData.access_token);
Another request uses that token in the Authorization header as Bearer {{token_abc}}.
But, it seems the token is valid only for one-time use: after request #2 is sent, the value of token_abc is reset to null in Environment variables - Current value.
What could be causing this? Because this is not how the application usually behaves - the token should be valid for 24 hours. Is there a Postman setting I'm not seeing somewhere? I'm using Postman 8.6.1.
For some reason unknown to me there are 2 "postman" object in the postman sandbox that you can use to set environment variables.
postman
pm
Both can call a function for setting variables on the variable scopes in postman. From what I gathered on forums discussing various postman problems, the usage of the postman object gets discouraged in favor of pm.
See if this helps:
//check if you get the value you expected first
console.log(jsonData.access_token)
pm.environment.set('token_abc', jsonData.access_token)
Since your variable gets reset somewhere, there must be code in your script responsible for that. You mention the variable gets reset after request #2, so the first place to look is in the "Tests" tab of your second request. You can use console.log(value) to output the value of that variable to console on various places in that script in order to further pinpoint the exact location in code where it gets reset.

Not able to parse Authorization Header

am calling an API with he query paramter as told by my Remedy team and i get the "Not able to parse Authorization Header" error
var yhttp = new XMLHttpRequest();
var phonedata=":People?q=%27Phone%20Number%20Business%27%20%3D%20%22%2B12017148030%22&fields=userid";
yhttp.open('GET', 'https://remproditsm.broadridge.net/api/arsys/v1/entry/CTM:People?q=%27Phone%20Number%20Business%27%20%3D%20%22%2B12017148030%22&fields=ciscofinesse');
yhttp.setRequestHeader('Authorization', 'Bearer' + response);
yhttp.setRequestHeader('Content-Type', 'application/json');
yhttp.send();
have tried AR-JWT instead of Bearer, have tried with application/json header and without, i was not convinced if i should be passing that in the header but remedy team advised me to pass it. Also, this works fine in Postman.
I propose to double check the postman and on the right side you have the CODE button,
then export working version from postman to JavaScript-XHR.
ok i found the issue, AJAx request by default is asynchronous, am using the varibale from the response as the token, and by the time it reaches the 2nd GET API request , it has nothing in the res variable, so i converted my first API request for token to synchronous
xhttp.open('POST', 'url',false);
xhttp.setRequestHeader('authString', 'authentication string');
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhttp.send(data);
res= xhttp.responseText;
document.write(res);
Yes, you need "AR-JWT {token}" as your Authorization header value. The token should be stored after the login call and used for each subsequent REST operation.
https://docs.bmc.com/docs/ars2008/examples-of-using-the-rest-api-to-get-update-and-delete-an-entry-from-a-form-929631054.html

Restrict some HTTP Methods on Postman

I need to restrict some of the HTTP Methods like PUT, POST and DELETE for my one of the environment. Is it possible in POSTMAN ?
This will help me in avoiding mistakes of doing POST,PUT or DELETE on my one of the environment.
You could add a variable to the Method dropdown - Add {{METHOD}} to the field and than add the same variable name in your environment file with the value you want?
You could also just delete the Methods you don't want to use from the dropdown, these can just be added in after, if you need it again.
https://learning.postman.com/docs/postman/customizing-postman/#customizing-request-methods
Postman does not provide any in-built functionality like this. However, you can use pre-request scripts for this. Write this in your pre-request script of the API you want to limit certain request methods-
var request = pm.request;
if(request.method.includes("POST") || request.method.includes("PUT")){
console.error("Inavlid request method");
throw new Error("Invalid request method");
}
The drawback of this approach is that you need to copy-paste this in every API's pre-request script. If you want to bypass that, you can cache this entire code into a postman variable and just eval that variable in every API. Steps-
Create an environment variable in your postman with this name as "my-script" and value as-
() => { var request = pm.request;
if(request.method.includes("POST") || request.method.includes("PUT")){
console.error("Inavlid request method"); throw new
Error("Invalid request method"); }}
Now just copy and paste this line in every pre-request script in your collection-
eval(pm.environment.get('my-script'))();