Access Cookies in Postman Native App Pre-Request Script - postman

Apologies if been asked before. Tried a quick search and couldn't find.
Situation :
The api is using an authentication token as a cookie name "abc-auth" and this is returned when i hit a /login endpoint. It is returned as a set-cookie header in the response which postman the native app happily accepts and sets up as a domain cookie in the ui
I hoped to basically as a pre-request step hit the login endpoint if the cookie doesn't exist but not hit it if we're already authenticated. So we only login once for the 20 requests rather than 20 times
I had hoped to do this accessing the pm.cookies object which I believe is now fully baked in to the native apps ref -> https://www.getpostman.com/docs/v6/postman/scripts/postman_sandbox_api_reference
So was hoping to do something like this
console.log(pm.cookies.toObject())
if (pm.cookies.has("abc-auth")){
console.log("Found Cookie");
} else {
//send the request
}
Expected :
That it runs the first time logs in and then next time finds the cookie and continues
Actual :
It never finds the cookie. Printing out the cookie list finds an empty array. I am seemingly unable to check cookies from the script.
Anyone know what I'm doing wrong?
A lot of the docs refers to interceptor but as the chrome app is being retired and native app was meant to assume that functionality I would really like the answer to be contained within the native app
Thanks!

Would something like this work for you to do the check:
if (_.keys(pm.cookies.toObject())[0] === "abc-auth"){
console.log("Found Cookie")
} else {
//Do something
}
It's using the Postman cookies function but also the Lodash keys function (which is comes with the native app) It's basically assuming that the first key is the one you want - That's probably not right as it might have several keys.

Related

Clearing Cookies Programmatically is not working in Postman and Newman

I need to be able to delete cookies automatically in between requests when they I run my collection of requests in Newman and Postman Runner (mainly Newman).
I followed the suggestion given in this comment by a person from Postman: https://github.com/postmanlabs/postman-app-support/issues/3312#issuecomment-516965288.
But it is not working.
The answer to these two SO questions also tell the same way to go about doing this: Postman: How do you delete cookies in the pre-request script?
Deleting cookies in postman programmatically
Here is the code that I use that the sources above suggest to place in the pre-request script:
const jar = pm.cookies.jar();
jar.clear(pm.request.url, function (error) {
console.log("Error: ");
console.log(error);
//handle error
});
[Note: error is logged as null when I run this code]
I have tried this code many times and also many different modifications of that code. I do white-list the domain too. But I always get the wrong response in the request. When I clear the cookies manually (using the cookie Manager UI dialogue box), the request gives the right response. I need help in determining where the problem could be for me in deleting cookies programmatically.
I also tried this to see what the cookies that I am deleting are:
jar.getAll(pm.request.url, function (error, cookies) {
console.log("Cookies:");
console.log(cookies);
console.log("Error: ");
console.log(error);
});
Here cookies is an empty array. Perhaps that is the problem. But that is very weird since when I check Cookie Manager manually, there are many cookies shown. And once I delete the cookies manually the requests return the right responses.
Another question I had was: What is the purpose of the callback functions that take 'cookies' and 'error' as arguments in the code above. Are these functions called everytime or only under certain conditions? Could not find the purpose of the callback functions in the postman documentation: https://learning.postman.com/docs/postman/sending-api-requests/cookies/
Thank you
If the cookie has "httpOnly" or "secure" header, you can't delete them via script in postman. jar.clear clears all the cookies except these httpOnly and secure ones.
I think this is a bug and needs to be fixed by Postman. If this is intended, there should be a setting in Postman to activate or disable it.

ckan.toolkit.redirect_to does not redirect

I'm currently developing an ckan extension, where i need to redirect to a url on a different domain.
In my plugin i defined a custom action function:
#side_effect_free
def download_json(context, data_dict):
toolkit.redirect_to('http://my.json-builder.com?id=1234')
But when i call this endpoint i just get following response:
response screenshot
So i assume that the action function is called, but the redirect_to call does not redirect to the url i defined.
Thanks for your help!
Florian
It's a bit hard to figure out what you're trying to accomplish but here's a few things I hope will help.
Short Answer:
No, you can't redirect from an API endpoint in CKAN. The endpoint response in CKAN is built up and expects certain things from your action. Your action should return some kind of result. In your case it's returning nothing but trying to redirect. A logic action function with IActions is not the same as a Blueprint or pylons controller action.
See Making an API request docs, specifically the breakdown of an API response in CKAN. Also, you can review the pylons implementation that builds up the API response or the flask blueprints implementation.
More Info to help with your approach:
You say you are trying to call an endpoint that redirects a user to a different domain url. Based on this consider the following:
The first thing I thought you wanted was to have a url that someone goes to through the web interface of your site and are redirected to another site. In this case your example code of toolkit.redirect_to('http://my.json-builder.com?id=1234') makes sense and works for a custom controller action using/implemented with IRoutes or if you're using flask then IBlueprint. A User would go to a URL on your site such as http://localhost.com/download_json and be redirected to the new URL/site in their browser.
If you are intending this to be an API call for other users this starts to feel a little bit odd. If a user is using your API, they would expect to get results from your site in JSON CKAN's API is designed to return JSON. Someone consuming your API endpoint would not expect to be redirected to another site e.g. if I called http://localhost.com/api/3/action/download_json I would expect to get a JSON object like
{
help: "http://localhost/api/3/action/help_show?name=download_json",
success: true,
result: {
...
}
}
They would look for success to make sure the call worked and then they would use the result to keep moving forward with their desired processes. If you do want someone via an API to get redirect info I'd likely return the redirect url as the result e.g. result: {'redirect_url': 'http://my.json-builder.com?id=1234'} and document this well in your extension's API docs (e.g. why you're returning this endpoint, what you expect someone to do with it, etc).
If this is an API call for your own extension I'm guessing what you are trying to do is use my.json-builder.com to build a json of something (a dataset maybe?) and return that json as the result at your endpoint or maybe even consume the result to make something else? If that's the case, then in your function you could make the call to my.json-builder.com, process the results and return the results to the user. In this case, you're not actually wanting to redirect a user to a new site but instead make a call to the new site to get some results. If you actually want the results for your extension you don't need an additional endpoint. You could make the call from your extension, consume the results and return the desired object you're trying to create.
Hope this helps and sorry if I've miss-understood completely.

Postman: How do you delete cookies in the pre-request script?

All the postman cookie-management answers I've seen refer to either the browser extension (open chrome, delete cookies viz interceptor etc) or with the app, using the UI to manually manage cookies.
I would like to delete certain cookies in my pre-request code as part of scripting my API tests. (delete them programmatically)
The Sandobx API docs mention pm.cookies so I tried
if (pm.cookies !== null) {
console.log("cookies!");
console.log(pm.cookies);
}
But the pm.cookies array is empty. Yet in the console, the GET call then passes a cookie.
There's also postman.getResponseCookies, which is null (I assume because we're in the pre-request section, not in the test section)
One answer suggested calling the postman-echo service to delete the cookie. I haven't investigated this yet, but it doesn't feel right.
new version now supports that since 2019/08, see more examples here: Delete cookies programmatically · Issue #3312 · postmanlabs/postman-app-support
Prerequisite
Cookie domains to be given programatic access must be whitelisted.
clear all cookies
const jar = pm.cookies.jar();
jar.clear(pm.request.url, function (error) {
// error - <Error>
});
get all cookies
const jar = pm.cookies.jar();
jar.getAll('http://example.com', function (error, cookies) {
// error - <Error>
// cookies - <PostmanCookieList>
// PostmanCookieList: https://www.postmanlabs.com/postman-collection/CookieList.html
});
get specific cookie
const jar = pm.cookies.jar();
jar.get('http://example.com', 'token', function (error, value) {
// error - <Error>
// value - <String>
});
According to the documentation pm API reference the pm.cookie API is only for the Tests tab, not for the Pre-request Script.
The following items are available in TEST SCRIPTS only.
pm.cookies
...
It seems that you will have to stick with this method : Interceptor Blog post
I know this is a very late answer, but for my case where I didn't want to use the cookies to start the execution of the collection, I just needed to uncheck the option "Save cookies after the collection run" and check the option "Run collection without using stored cookies" on the Runner panel.
And then if I want to manage the cookies on my own, I created a first request on the collection and used the Tests tab just to collect the cookies that I wanted and saved them on a variable.
pm.environment.set('cookie', pm.cookies.get('csrftoken'))
pm.environment.set('sessionid', pm.cookies.get('sessionid'))

Missing Cookie causing 401

I am making a (forms)authentication module(HTTPModule) for IIS that reads authentication from the login page, sets a cookie and redirects. All works great on all sites and sub applications. Because the module also protects webservices I build in a part that also reads the authorization header. Because these services should also be accessed from other tools.
Now I got to the point I actually protect a webservice, all great and with the auth header to the request I can indeed always get to the webservice but I can ONLY access it with the header active(and after every request I get another cookie).
If I try to access it with my normal login, where I also access other sites under the same protection with then I get redirected back to the login page :S. I really do not understand why this is happening.
PS HttpContext.Current.Request.IsAuthenticated is always false in my module when accessing the service, but my code is:
if(!HttpContext.Current.Request.IsAuthenticated){
if(Forms["Username"] != null){
//do authenticatoin & setCookie and Principle
}
}else{
if(AuthHeader is there){
//do authenticatoin & setCookie and Principle
}
}
Naturally with every request now it authenticates and sets the principle for each request. But why oh why does it not see(send) my cookie while other applications do see it? (with the exact same module)
The OnAuthenticateMethod also does not receive the FormsAuth ticket/cookie but does receive other cookies I set.
Things I already checked:
* web.config authorization is correct.
* Machine keys are set for cookies.
* Cookie names are similar
* .ASPXAUTH cookie does not get send towards OnAuthenticateMethod, but it does get send by the browser in the Cookie header.
I am lost on why this happens.

Writing multiple cookies to Java HTTP Response (HttpSlingServletResponse) not working

I am trying to write multiple cookies to a SlingHttpServletResponse, however only the last cookie i write is visible in the browser.
Ex.
response.addCookie(new Cookie("foo", "bar"));
response.addCookie(new Cookie("lion", "bear"));
response.addCookie(new Cookie("cat", "dog"));
When I look at the cookies on my browser, the only cookie i see is the: "cat", "dog" cookie
If i switch the order, the last cookie is always the one that displays (so i dont think its something with a specific cookie).
The Java API indicates that you can call response.addCookie() any number of times to add any number of cookies.
Im not sure if this is a Sling specific issue (i dont think it would be) but it might be?
Looking at the code, I suspect this is an issue of the underlying servlet container used.
By default Sling uses the Jetty 6 Container contained in the Apache Felix Http Bundle.