I would like to have a script running before each request in Postman, which renews the OAuth token, if it is expired (or is about to). So I found this blog on the topic and wanted to implement that.
However, the way I usually request tokens where I work, is by sending information via the body. In this picture, you can see how it looks in Postman.
This works just fine and retrieves a token for me, when I click send. Now I tried to use this information, to modify the script from the blog, so it now looks like this:
// Refresh the OAuth token if necessary
var tokenDate = new Date(2010,1,1);
var tokenTimestamp = pm.environment.get("OAuth_Timestamp");
if(tokenTimestamp){
tokenDate = Date.parse(tokenTimestamp);
}
var expiresInTime = pm.environment.get("ExpiresInTime");
if(!expiresInTime){
expiresInTime = 300000; // Set default expiration time to 5 minutes
}
if((new Date() - tokenDate) >= expiresInTime)
{
pm.sendRequest({
url: pm.variables.get("base_url_token"),
method: 'POST',
header: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: {
grant_type: 'password',
username: pm.environment.get("username"),
password: pm.environment.get("password"),
client_id: pm.environment.get("client_id_practice_app"),
client_secret: pm.environment.get("client_secret_practice_app")
}
}, function (err, res) {
pm.environment.set("OAuth_Token", res.json().access_token);
pm.environment.set("OAuth_Timestamp", new Date());
// Set the ExpiresInTime variable to the time given in the response if it exists
if(res.json().expires_in){
expiresInTime = res.json().expires_in * 1000;
}
pm.environment.set("ExpiresInTime", expiresInTime);
});
}
When I run any request, it shows in the console that the pre-request script has correctly sent the auth request. But I get the following error in the response body (from the auth):
{"error":"invalid_client"}
I am almost certain that it is getting the correct Id and Secret. I have tried swapping the environment variables for hardcoded values. But I am less sure if I am setting the body correctly.
Can anyone tell me how to get this to work?