Auto fetch OAuth2 access token in POSTMAN before calling the API

Karanbir Singh
3 min readOct 17, 2019

Agenda

The agenda here is to pre-fetch the OAuth2 access token automatically using POSTMAN before hitting the API protected by it.

My motivation — that one particular day, that one minute and that one particular second when, I was frustrated of doing same thing again and again, i.e fetching the OAuth2 access token manually from the token endpoint before hitting the actual service.

So I came up with an idea of automating the flow, which includes:-

  1. Fetching the access token before accessing the protected(OAuth2 protected) API.
  2. Storing that somewhere in the POSTMAN(using the POSTMAN).
  3. Accessing the saved/stored access token in the headers of that particular request.

Check the POSTMAN version

Please check the POSTMAN version, this may not work for all the versions and this was tested on v7.9.0 as seen in the screen shot below. Though I am hopeful that some closer versions should also work. But older ones were having some issues with one of my friends.

Steps to follow:-

Step 1. Open a new tab in the postman. For creating a new request, add your url and other things like you would already be doing. Important thing is to open the tab Pre-request Script tab like below:-

Step 2. Paste the below script inside that tab for Pre-request Script

The Script(simple JavaScript code) can be found below as a gist:-

pre-request Script

Step 3. Change the Authorization header as below:-

key is Authorization and value is Bearer {{access_token}}, access_token is being set in the pre-request script by setting an environment variable named access_token, that can be seen on the following line:-

pm.environment.set("access_token",responseData["access_token"]);

Step 4. Finally, hit Send button to hit the API that is protected using OAuth2. Well this was an obvious step 😀, because you we will have to trigger the Send action to call your API.

Step 5. For debugging the script that we used above, one can open the postman console as per the screen shot below:-

Once the console window opens you should see something like the attached screen below. This should work, if you comment out these particular line(s) on the script.

console.log(JSON.stringify(postRequest)); // this one to check the requestconsole.log("access_token is ---> "+responseData["access_token"]); // this one to check the access token we get back

I did not feel like sharing the access token as it was a JWT. So that was blurred.

That was it, a Lazy developer = an efficient developer (not always though😀)

--

--

Karanbir Singh

API developer + Web Application developer + Devops Engineer = Full Stack Developer