Simplify bearer token auth flow in Postman

If you’re developing API’s chances are you are using Postman to test or debug them.
If not, you should totally consider giving it a try, it’s possibly the best productivity tool out there in terms of playing with APIs either developed by you, or someone else.

In this article I want to present you a flow that you can use when working with APIs that require a bearer token for authentication.

Normal flow

  1. Get a token from a /token endpoint

  1. Copy that token into the the authorization / bearer type field in the request that you want to make next using the authentication token you just got. Repeat this for all request.

This will work on a small scale, but it can get really annoying when the token expires and you have to re-copy it in every place.

Automating token refresh

The solution is to somehow automate the token refresh process. To do this we will use 2 very neat features of Postman: Environment variables and Tests.

  1. Create an environment variable to store the token and reference the variable in all the API requests.

This already takes us more than halfway there since whenever your token expires you can update in one place only and not in every call. But we want to not even have to copy it.

  1. Save the token in the environment variable when you call the /token endpoint. To achieve a post-request operation you can use the Tests feature of postman. I’m not going to dive into the Tests and Pre-request functionalities of Postman (that can be the subject of another article or you can read all about it in the docs)

Here’s the “test” you have to put in your /token call to save your token in the variable:

1
2
3
4
5
    pm.test("GetToken", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.access_token) !== "";
pm.environment.set("token", jsonData.access_token);
});

Once this is done, all you have to do is call the /token request every time the token expires, and all the other endpoints will get updated automatically.

Share Comments