DEV Community

Cover image for How to Automate Authorization Token Header for Postman Request
Dias
Dias

Posted on • Updated on

How to Automate Authorization Token Header for Postman Request

Hi guys.. this is my first story on Dev.to, pardon for my bad English, i'll always improve my english skills xD


I always use Postman for testing an API if it's works as expected or not.
But sometimes it's painful when you forgot to refresh Authorization token and get message like 'Expired token' from API response and need to switch between postman tabs to generate new Authorization token and back to current tab for paste new token, not efficient, right ?

So.. i'm start digging to Postman documentation and search about how to create event that fired before request send, and i found Pre-Request Scripts feature on Postman.

Pre-request scripts are snippets of code associated with a collection request that are executed before the request is sent. This is perfect for use-cases like including the timestamp in the request headers or sending a random alphanumeric string in the URL parameters.
Pre-request scripts

Yipeee!!! We can set headers automatically before sending request, FYI
pre-request scripts are written in Javascript and it's not a big deal since it's not hard to write simple http request on Javascript.

Before we start, i will use Postman variables feature to store value on collection scope, so here we go..

Step 1 - Create global variable

We need to 'save' token information so we can use it from anywhere.
Create 2 variables : 

  1. expiryTime
  2. activeToken I'm create my variable on collection scope Click three dots on your collection

global variable

Click Variables tab and fill the form

fill form

Step 2 - Create simple pre-request scripts

Open Pre-Request Scripts tabs and write this codes

const getAuthToken = {
    url: 'https://localhost:8243/login',
    method: 'POST',
    header: {
        'Content-Type': 'application/json',
    },
    body: {
        mode: 'application/json',
        raw: JSON.stringify({
          client_id: '<Your client_id>',
          client_secret: '<Your client_secret>'
        })
    }
}

var isTokenExpired = true;
var activeToken = pm.environment.get('activeToken');
var expiryTime = pm.environment.get('expiryTime');

if (!activeToken || !expiryTime) {
  console.log('empty active token or expiry date, should generate new one');
} else if (expiryTime <= (new Date()).getTime()) {
  console.log('token expired, generate new one');
} else {
  isTokenExpired = false;
}


if (isTokenExpired === true) {
    pm.sendRequest(getAuthToken, function (err, res) {
        if (err === null) {
            var response = res.json();

            // Save token to activeToken variable
            pm.environment.set('activeToken', response.access_token)

            // Calculate expiry date and save to expiryTime variable
            var expiryDate = new Date();
            expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);
            pm.environment.set('expiryTime', expiryDate.getTime());
            console.log('saving token')
        }
    });
}
Enter fullscreen mode Exit fullscreen mode

A few notes :

  • Postman have built in function, on example you'll find function pm.environment.set and pm.environment.get, if you need more information, you can check to official Postman documentation. You can modify body payload to fit your API needs.

Step 3 - Use auto generated token for authorization

After we create pre-request scripts, we need to implement token for whole collection.
Open Authorization tab and fill empty token field with activeToken it means we use variable that previously have been filled with token.

authorization tab

Step 4 - Implement token

In previous step we've done for setting up auto generate token, and this is final step to implement it.

Open your Request under same collection as we setup before and go to Authorization tab, on Type field select Inherit Auth From Parent, congrats you're done!

For now, every request you made, it will fire pre-request scripts. If you want to see where console.log command print the content, it will printed on Postman Console. Click terminal icon on bottom bar Postman
postman bar

Console form will showed up

postman console

I hope it will boost your workflow to be more efficient.

Anyway.. i made Digital Wedding Invitation service, register for free
undangan nikah online

Technology and startup news
Berita Seputar Teknologi, Tutorial dan Informasi Terkini

Top comments (0)