For a long time, I was doing something that just felt a bit wrong but it worked so I went with it, until I found an awesome community member, that decided to share their work to a wider audience. I can’t stress enough how important it is to do that, you may feel that what you’re doing is not going to be of any use to people but I can assure you….It really is!!
For a while, I was getting an Authentication Bearer token for my API requests…kinda manually, I wasn’t physically copying and pasting but I might as well of done this each time. I was already making use of the Pre-request Scripts and the environment variables but my Auth request, that I set up, was happening before every request, instead of checking to see if the token was actually still valid first – In hindsight, the way I had it was awful but because it wasn’t adding any real noticeable latency, I just kept my collections as they were, I knew that I was sending unnecessary requests each time but I was semi-fine with that happening.
I mentioned before about the importance of sharing what you do, Ben Chartrand did just that in this blog post, this was exactly what I was looking for and it was simple enough to understand straight away – again, that’s always good when you’re sharing your knowledge.
It seems pretty pointless, basically sharing Ben’s work again in another post but as I have been recently using the built-in modules like Moment and Lodash within Postman, I changed the script slightly to use these modules and refactor the code while doing so. It’s only a small difference and all the credit should absolutely go to Ben for getting the original script together in the first place.
So what have I done differently…

The main change has been around the first ‘If‘ statement – In Postman, you can return all the environment variables, in a JavaScript object, by using the ‘pm.environment.toObject()‘ function . Using the Lodash _.has function, I’m looking within that object to see if it contains the ‘AccessTokenExpiry‘ or ‘jwt‘ properties, If it doesn’t… It’ll go and get a new token.
As well as this check, I’m also checking to see that the ‘AccessTokenExpiry‘ value (in milliseconds) is still valid. This is checking against the current date and time. This date is returned in milliseconds using the ‘moment().valueOf()‘ function. Love this site as a quick reference to convert milliseconds into a human readable date and time.
The only other difference is in the ‘pm.sendRequest()‘ function where I’m using momentjs once again, to set the ‘expiryDate‘ value by taking the current time in milliseconds and then adding the ‘expires_in‘ response value to this time. This will then give us a time in the future that the token will expiry. If we send a new request and the token has expired – we will hit one of the first ‘If‘ statement conditions and it will go and get another valid token. Simple.
I have different files created for each of my environments so it’s just a case of switching between these files, If I want to run requests locally, in Staging or on Production.
My environment files would hold the ‘AuthData‘ and the ‘tokenBaseURL‘ variable values that are referenced in the Pre-request Script.

The ‘AuthData’ value is the ‘client_id’ and ‘client_secret’ values that have been base64 encoded – This can be encoded using any of the online tools out there such as https://www.base64encode.org/ or you could just modify the token script slightly to add those raw values straight into the request or as separate values in the environment files. Your context and personal preference will help you choose with method you use.

That’s it, like I mentioned before, the majority of the work has been done by Ben. By him sharing the original information with a wider audience, It has helped me and many others use the Postman application in a more efficient way and I can only say huge thank you for that.
I’ve added the code here so you can have a closer look at what’s going on in your own local instances:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This can be placed in the Pre-requests on the collection level. | |
// It will check to see if certain valid variables are present in an environment file. | |
// If these are not present, it be go and get another valid token | |
// The 'AuthData' variable is a Base64 encoded client_id and client_secret | |
// This my need to be tweaked for your needs but the mechanism will work. | |
const moment = require('moment') | |
const getJWT = { | |
url: `${pm.environment.get('tokenBaseURL')}/Auth/connect/token`, | |
method: 'POST', | |
header: { | |
'Content-Type': 'application/x-www-form-urlencoded', | |
'Authorization': `Basic ${pm.environment.get('AuthData')}` | |
}, | |
body: { | |
mode: 'urlencoded', | |
urlencoded: [ | |
{key: 'grant_type', value: 'client_credentials'}, | |
{key: 'scope', value: '<scope details>'} | |
] | |
} | |
} | |
var getToken = true | |
if (!_.has(pm.environment.toObject(), 'AccessTokenExpiry') | |
|| !_.has(pm.environment.toObject(), 'jwt') | |
|| pm.environment.get('AccessTokenExpiry') <= moment().valueOf()) { | |
} else { | |
getToken = false | |
} | |
if (getToken) { | |
pm.sendRequest(getJWT, (err, res) => { | |
if (err === null) { | |
pm.environment.set('jwt', `Bearer ${res.json().access_token}`) | |
var expiryDate = moment().add(res.json().expires_in, 's').valueOf() | |
pm.environment.set('AccessTokenExpiry', expiryDate) | |
} | |
}) | |
} |
Paw REST client. Copy and paste the bearer token from a response and it magically turns it into a dynamic variable for other requests. It’s that simple. Postman is useful for collaboration, but the UI and UX of it is terrible.
Thanks for the tip – Useful to know. Kinda tricky to do on a Windows machine though 😉
Reading this comment again, why do you need to copy and paste something? Can’t you set that variable automatically from the response data?
Great article Danny!
Just wanted to suggest you an improvement.
Instead of
“`
if (!_.has(pm.environment.toObject(), ‘AccessTokenExpiry’)
|| !_.has(pm.environment.toObject(), ‘jwt’)
“`
You can use the pm.environment.has as [documented here](http://www.postmanlabs.com/postman-collection/VariableList.html#has)
“`
if (!pm.environment.has(‘AccessTokenExpiry’)
|| !pm.environment.has(‘jwt’)
“`
Nice – not really sure why I used ‘_. has’ now… I think I’ll update my script and change to use your approach. 🙂
I’m still a novice coder so all refactoring suggestions are very welcome.
Thanks again!