16

I'm using Postman to test and play with an API.

For the login url, the API requires sending a POST request with username and password as fields. I do this, and I get a 200 response with the message that I am logged in.

I then try another request to get user data. However, I get a response that I am not logged in.

I realized this problem is most likely because the cookie that is sent to me when I log in is not included in the next Postman request.

So my question is, how do I save and include cookies for future requests?

CodyBugstein
  • 21,984
  • 61
  • 207
  • 363

4 Answers4

10

Store the cookie value you want to use in a global variable.In Tests tab of login request, write

postman.setGlobalVariable('key', postman.getResponseCookie("cookieName").value);

Pass along with the value in the Headers tab as a cookie in get user request:

Cookie | cookieName={{key}}
Ashutosh
  • 2,827
  • 2
  • 12
  • 11
4

I tried using Ashutosh's answer but got an error. I'm guessing this is because Postman's scripting API changed?

At any rate, the following worked for me:

  1. In the Tests tab of the request that will return cookies you want to save, write
pm.globals.set('<your key>', pm.cookies.get('<cookie name>'));
  1. Then, as described in Ashutosh's answer, add the cookie to the headers by setting the key as cookie and corresponding value as <your cookie name>={{<global variable name>}};.

I found documentation for this at the Postman sandbox API reference.

darksinge
  • 1,828
  • 1
  • 21
  • 32
3

(Using the native Postman app without the interceptor) The traditional way of reading the cookie does not work for me pm.cookies.get('<cookie name>') . Here is a workaround that automatically attaches auth cookie to all requests within a collection:

// The test scripts below run after the api /login returns the response

const authCookie = pm.response.headers.idx(3).value
/* 
pm.response.headers.idx(3) is equal to:
{key: "Set-Cookie", value: "xs=eyJhb; Max-Age=3600; Path=/; Expires=Fri, 18 Dec 2020 04:40:34 GMT; HttpOnly; Secure; SameSite=None"} 
*/

const token = authCookie.substring(3, authCookie.indexOf(';'))
pm.collectionVariables.set('xs_value', token);

Then add this pre-request scripts to the entire collection:

// Scripts below runs before any request within a collection is sent

const token = pm.collectionVariables.get('xs_value')
pm.request.headers.upsert({ key: 'Cookie', value: `xs=${token}` })

Enjoy!

More info on how to attach headers to requests

Son Nguyen
  • 2,991
  • 2
  • 19
  • 21
0

It seems there are two Interceptor plugin in google chrome. make sure install the correct one.

Ali Nikneshan
  • 3,500
  • 27
  • 39