DEV Community 👩‍💻👨‍💻

Cover image for Automatic authorization in Postman 🔒
Iacovos Constantinou
Iacovos Constantinou

Posted on • Updated on

Automatic authorization in Postman 🔒

Working with short lived JWTs can be painful when you don't have an automated mechanism in place to refresh the token. This is quite common when setting up a new collection in Postman.

In this post we will be looking on how we can automate this, so that we retrieve, refresh and use the token right before each API call.

Environment configuration

Before we get started, we need to define a few environment variables in Postman. These are:

  • baseUrl API URL
  • username The username to connect with
  • password The password for the above username

Unfortunately, there's no way to display the password as a ... password field. Postman will store and display everything in clear text, so have that in mind.

Pre-request script

Then, we need to edit the collection and configure the Pre-request script code. To do that, right click on the collection, select edit and then "Pre-request scripts"

Here is an example. As you can see the implementation is quite generic so most likely you will need to adjust a few things to make that work for you.

How it works

Initially we check whether we have a token stored. If not we go ahead and retrieve a new one along with expiration time.

We store both in environment variables. You don't need to create these variables, the script will create them whenever necessary.

If the token exists, we check also whether it has expired. In that case, we refresh the token and similarly to above we store the new token and its expiry date.

In either case, the token will be stored in a new environment variable called accessToken. This can be used to define the default authorization method. To do this right click on the collection, select edit, then Authorisation and use the variable {{accessToken}}.

Conclusion

I hope you find this approach useful and hopefully it will save you from some time from manual actions.

Make sure to follow me on dev.to, Medium or Twitter to read more about PHP, Docker and other dev topics.

Top comments (1)

Collapse
 
valiahavryliuk profile image
Valia Havryliuk

We've just published a good article, on how to discover the PandaDoc API with Postman in a few clicks medium.com/the-pandadoc-tech-blog/...

🌚 Life is too short to browse without dark mode