Refreshing tokens with authorization code grant flow

Hi Postman team,

I have an API that requires oAuth2 authentication with bearer token. I successfully managed to get a bearer token from my collection’s Authorization tab using code grant flow. It asks me to login, to grant access to the data and eventually I get back both an access token and a refresh token. This is working great.

What I’d like to do next is to call the refresh token endpoint of my API to essentially get a new access token as the first step of running my collection.

I tried to add a script in my collection’s Tests tab to capture the access and refresh tokens values found in the response body. So I tried the below script:

pm.test(“access_token and refresh_token must exist”, function () {
pm.expect(pm.environment.has(“access_token”)).to.equal(true);
pm.expect(pm.environment.has(“refresh_token”)).to.equal(true);
var jsonData = pm.response.json();
pm.environment.set(“access_token”, jsonData.access_token);
pm.environment.set(“refresh_token”, jsonData.refresh_token);
});

I was hoping it would set the environment variables after successfully authenticating for the first time, and reuse those values in my refresh token request.

I suspect pm.response is empty because I acquired the access and refresh tokens from the collection’s Authorization tab and not from a regular request.

Is there any way to achieve similar result?

Thank you for your input!

Your assumption is correct, @mazerab. Since you are not sending the OAuth2 requests from a regular Postman request, you also don’t get access to the body.

There are two ways to do this:

  1. Manually copy / paste the token and store it in a variable. You cannot get an access token without a manual step, so for that reason, automating only the last part may provide you with little value. Once you have a refresh token, you can get a new access token before the refresh token expires and you can automate this step.

  2. Create the /oauth2/token request where you exchange the authorization code for an access token. In this way, you can read the access token and the refresh token from the response.

1 Like

I think still there will be a problem.
I have the same setup for getting the access_token and refresh_token using Authorization from a collection.
though I can copy and past the refresh token, write a pre script to get the new token but I can’t be able to write it to same place when Postman it self writes.

so the problem will be, “inherit auth from parent” will not work because Postman still hold the old token.

I think this should be a necessary feature request. to give access to the token with read and write access.

@Jayantnd Just stop using the Postman Auth2 helper, you don’t needed.
Just manually set the Authorization header.

Yeah that is the work around, I am currently using. but this way we can’t take advantage of Postman’s Auth2 Helper.
I and many developers believe this auto refreshing feature will be great to have.