Automatic authorization in Postman 🔒

Cover image for Automatic authorization in Postman
Photo by iMattSmart on Unsplash

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.

1/**
2 * Ensures that we have a valid token before any request.
3 *
4 * To use this, you need to edit the Collection
5 * 1) select "Bearer Token" and provide `{{accessToken}}` as the Token, under Authorisation tab.
6 * 2) copy this script into "Pre-request scripts"
7 *
8 * Last, you need to define the following variables under the Environment
9 * baseUrl : API URL ie https://example.com/
10 * username: The username to connect with
11 * password: The password for the above username
12 */
13const tokenExists = pm.environment.get('accessToken') && pm.environment.get('expiresOn');
14if (tokenExists) {
15 const tokenExpired = pm.environment.get('expiresOn') <= (new Date()).getTime() - 30;
16 if (tokenExpired) {
17 // Token expired so we are renewing
18 const refreshTokenRequest = {
19 url: pm.environment.get('baseUrl') + '/api/session/token',
20 method: 'POST',
21 header: 'Content-Type:application/json',
22 body: {
23 mode: 'application/json',
24 raw: JSON.stringify({
25 refresh_token: pm.environment.get('refreshToken')
26 })
27 }
28 };
29 pm.sendRequest(refreshTokenRequest, (error, response) => {
30 if (error !== null) {
31 console.log(error);
32 return;
33 }
34 
35 const data = response.json();
36 const expiresOn = new Date();
37 expiresOn.setSeconds(expiresOn.getSeconds() + data.expires_in)
38 pm.environment.set('expiresOn', expiresOn.getTime());
39 pm.environment.set('accessToken', data.access_token);
40 });
41 }
42} else {
43 // Token not found so we are creating a new session
44 const newTokenRequest = {
45 url: pm.environment.get('baseUrl') + '/api/token',
46 method: 'POST',
47 header: 'Content-Type:application/json',
48 body: {
49 mode: 'application/json',
50 raw: JSON.stringify({
51 username: pm.environment.get('username'),
52 password: pm.environment.get('password')
53 })
54 }
55 };
56 
57 pm.sendRequest(newTokenRequest, (error, response) => {
58 if (error !== null) {
59 console.log(error);
60 return;
61 }
62 
63 const data = response.json();
64 
65 const expiresOn = new Date();
66 expiresOn.setSeconds(expiresOn.getSeconds() + data.expires_in)
67 pm.environment.set('expiresOn', expiresOn.getTime());
68 pm.environment.set('accessToken', data.access_token);
69 pm.environment.set('refreshToken', data.refresh_token);
70 });
71}

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.toMedium or Twitter to read more about PHP, Docker and other dev topics.

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
Cover image for Faster Docker builds with composer install

Faster Docker builds with composer install ⚡

Next Post
Cover image for Deploy to AWS ECS with Github actions

Deploy to AWS ECS with Github actions 🚀

Related Posts
Cover image for Proactive monitoring with Angular and Datadog

Proactive monitoring with Angular and Datadog

Being proactive is essential for any application whether that concerns the API, the web or mobile application. You can capture errors as they happen, with zero involvement from application users. Then of course you can work to fix the error, contact end users or whatever might seem appropriate on each case.
Read More