2

Our teams use Postman to explorative testing of API. However, for protected endpoints we need to:

  1. Authenticate and retrieve session tokens: SESSION and XSRF (we have the endpoint returning both as JSON).
  2. Add SESSION cookie and XSRF header to every request.

This is laborious. Is there a way to simplify that process with Postman?

Can Postman parse tokens out of the endpoint and add them to every HTTP request? How?

2

Add the following code to the "Tests" script for your authentication request. This script is executed upon receipt of the response. Modify the parts in <> to match the response given.

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("cookie", jsonData.<path_to_your_cookie>);
postman.setEnvironmentVariable("xsrf", jsonData.<path_to_your_header>);

Now, in your headers, you can access your saved variables by wrapping the variable names in double brackets: {{cookie}}, {{xsrf}}.

Every time you re-authenticate, those variables will automatically be over-written with the new, valid values.

There may be a cleaner way to do this, especially with newer versions of Postman, but this is what I use to handle OAuth with my requests and it works quite well.

  • Thanks. This work (with some slight changes to the syntax). But still I need to remember to include variables in each request. Is there a way to define these headers/cookies only once, and then Postman will in inject them for all requests in the collection? – dzieciou May 8 '18 at 22:50
  • 1
    That isn't information I've personally ever sought out. What I've done is to save an empty request that has all of the necessary headers and the variables to populate them. Then, instead of creating a "new" request, I will open the empty one and "Save As". It's sort of a hacky workaround, but it makes things easy enough that I've never found it necessary to put effort into finding another way. – VanderLinden May 9 '18 at 18:00
  • let cookie = postman.getResponseHeader("Set-Cookie"); postman.setEnvironmentVariable("cookie", cookie); Sets the cookie – eMad Aug 10 '19 at 13:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.