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

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'))

Related

Problems with AWS Amplify, Next.js and authenticated SSR

I've got a Next.js application that uses AWS Cognito userpools for authentication. I have a custom UI and am using the aws-amplify package directly invoking signIn/signOut/etc... in my code. (I previously used the AWS Hosted UI and had the same problem set out below - I hoped switching and digging into the actual APIs who reveal my problem but it hasn't)
Everything in development (running on localhost) is working correctly - I'm able to login and get access to my current session both in a page's render function using
import { Auth } from 'aws-amplify';
...
export default const MyPage = (props) => {
useEffect(async () => {
const session = await Auth.currentSession();
...
}
...
}
and during SSR
import { withSSRContext } from 'aws-amplify';
...
export async function getServerSideProps(context) {
...
const SSR = withSSRContext(context);
const session = await SSR.Auth.currentSession();
...
}
However, when I deploy to AWS Amplify where I run my staging environment, the call to get the current session during SSR fails. This results in the page rendering as if the user is not logged in then switching when the client is able to determine that the user is in fact logged in.
Current Hypothesis - missing cookies(??):
I've checked that during the login process that the AWS cookies are being set correctly in the browser. I've also checked and devtools tells me the cookies are correctly being sent to the server with the request.
However, if I log out context.req.headers inside getServerSideProps in my staging environment, the cookie header is missing (whereas in my dev environment it appears correctly). If this is true, this would explain what I'm seeing as getServerSideProps isn't seeing my auth tokens, etc... but I can't see why the cookie headers would be stripped?
Has anyone seen anything like this before? Is this even possible? If so, why would this happen? I assume I'm missing something, e.g. config related, but I feel like I've followed the docs pretty closely - my current conf looks like this
Amplify.configure({
Auth: {...}
ssr: true
});
Next.js version is 11.1.2 (latest)
Any help very much appreciated!
You have to use Next#11.0.0 to use getServerSideProps, withSSRContext and Auth module in production.
I had same issue.
My solution was that disconnect a branch has an authentication problem once and reconnect the branch.
What are your build settings? I guess you are using next build && next export in which case this getServerSideProps shall not work. See https://nextjs.org/docs/advanced-features/static-html-export#unsupported-features
To use SSR with AWS amplify see https://docs.aws.amazon.com/amplify/latest/userguide/server-side-rendering-amplify.html#redeploy-ssg-to-ssr or consider deploying on a node server that is actually a server that you can start with next start like AWS EC2 or deploy on Vercel.
Otherwise if you use next export have to make do with client side data fetch only with client side updates only and cannot use dynamic server side features of nextjs.
One reason for context.req.headers not having any cookie in it is because CloudFront distribution is not forwarding any cookies.
This “CloudFront Behaviour” can be changed in two ways:
Forward all cookies, OR
Forward specified cookies (i.e. array of cookie names)
To change the behaviour, navigate to CloudFront on AWS console > Distributions > your_distribution > Behaviors Tab.
Then Edit existing or Create new behaviour > Change cookies settings (for example set it to "All")

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.

While Running postman collection through Newman how to clear cache/Cookies during each iteration

While running collection for n iteration - I get desired result during first iteration but for all subsequent iteration as session cookies are stored I don't get desired Response as it is cookies are stored
To clear cookies you have to write a script to delete the cookies for the domain you are accessing. Something like this:
const jar = pm.cookies.jar();
jar.clear(pm.request.url, function (error) {
console.log(error);
});
but first you have to whitelist your cookies before trying to delete them. To whitelist cookies, click on the "Cookies" tab under Postman request page, then click on Whitelist and add your domain.

Access Cookies in Postman Native App Pre-Request Script

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.

Google Analytics ID stored in cookie is undefined

We are installing google analytics via Google Tag Manager.
We have custom variable that supposed to take the GA customer id, and send it to our GA.
The variable is defined as follows:
function() {
try {
var cookie = {{GA_ID_Cookie}}.split(".");
return cookie[2] + "." + cookie[3];
} catch(e) {
return 'N/A';
}
}
While {{GA_ID_Cookie}} is a first party cookie variable named "_ga".
In most cases, this values works, but there are some cases where GA_ID_Cookie is undefined (and exception is thrown).
It happens in all browsers. There enough users with "N/A", so its not about cookies disabled issue.
The GTM installs the GA on page view event; It uses this problematic variable as a custom dimension.
My question is how come the ga id is null, and how can we overcome this problem and get the id in other ways.
It is likely that your tag is fired before the cookie is generated.
Try to change the page view to window load. Clear the cookie and retry, it should work.
Like Ashley pointed out you might be facing a race condition whereby you try to access the cookie before it is set by GA.
Please note that the GA cookie ID contains some uninteresting info from the point of view of identifying users, namely the version which should be removed.
If your GA cookie looks like this:
_ga=GA1.2.1033501218.1368477899;
Then the part you're interested in is:
1033501218.1368477899
To retrieve the client ID via the browser, the official way is as follows:
https://developers.google.com/analytics/devguides/collection/analyticsjs/accessing-trackers
// Initializing the `ga` command queue so that commands
// can be queued even if the GA snippet is not loaded
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
// Queuing a command to retrieve the Client ID when the tracker is ready
ga(function(tracker) {
// Logs the client ID for the current user.
console.log(tracker.get('clientId'));
});
If you are using GTM then you need to create a task:
https://www.simoahava.com/analytics/13-useful-custom-dimensions-for-google-analytics/#13-client-id
function() {
return function(model) {
return model.get('clientId');
};
}
If you want to retrieve the Client ID via the server, then you simply need to parse the cookie HTTP header (below example is from request to stackoverflow website) using an HTTP library of your choice and getting rid of the leading GA\d\.\d\. pattern which represents the cookie version.
cookie: prov=f67bae3b-f99c-2f22-84fc-7c2a62862f3d; _ga=GA1.2.1380536973.1571212618; ...