How can I set Postman to automatically get a new OAuth2 token when the previous one expires? Would be nice to either just have a quick button och even better for it to check when sending the request.
Hi @simfre,
Welcome to the community!
This should be fairly straight forward, but before I layout some code, I am going to make some assumptions.
If you get an expiration time with each issuance of an access token (in general OAuth2 implementation, you should), you can store that token and expiration time in environment variables.
Then each time you make a request, you compare the current time to the time you got from the token by pulling down that environment variable. If the current time is greater than the time from the token, we know it has expired. Then you use pm.sendRequest
method to get another access token, store the token and time as environment variables again, for use in your main request. Else, the current time is less than the token time, it has not expired, and you can skip getting the new token.
Thats the process that I would lay out, I hope it makes sense.
Without further detail on how your OAuth2 request looks, I canβt add much additionally here.
Here is some general pseudo code that should explain it.
var token_time = pm.environment.get("token_time");
var access_token = pm.environment.get("access_token");
// Check if Token expired
if ( Date.now() > token_time ) {
pm.sendRequest(...)
// Parse response to get new token and token time, set as env variables
pm.environment.set("token_time", new_token_time);
pm.environment.set("access_token", new_access_token);
};
Hope this helps!
Regards,
Orest
We also have a thread on this subject here:
Thanks for these hints. Iβm surprised there isnβt just a refresh button, or something like pm.reauthorize() to call. Could it be implemented? Rather than reinventing the wheel with these scripts.