How to access inherited authorization in request`s pre-req. script?

When using oAuth 2.0 Authorization on a request…
image
…you can easily access the accessToken from the request via

pm.request.auth.oauth2.get('accessToken')

However, when you use the “inherit auth from parent” as authorization…
image
…you cannot.

I’ve already tried…

pm.collectionVariables.auth.oauth2.get('accessToken');

… since the oAuth 2.0 authorization is set up in the collection, but also this won´t work.

Similar threads i found to this topic - but no solution to the problem is given:
Reading Authorization header in pre-request script - Help - Postman
Determining auth type in a pre-request script - Help - Postman

1 Like
  1. Make the authorization call
  2. In the Test tab, extract the token and store it as a collection variable.
  3. At the collection level, in the authorization tab, set the authorization as the collection variable set in the authorization call.

Then all other requests in the collection can inherit from the parent - collection

The huge benefit of using the oAuth 2.0 Authorization Feature of Postman is to switch between multiple sessions via the “Manage Token” dropdown without having to re-login. Also you can make use of the “auto-refreh token” feature that way. By switching between sessions the “tests” tab is not executed.
When setting up a manual authorization request you loose the benefit described above.

So thanks for the hint, but this does not help me that concern.

Hey @dnlschls,
I was able to get the accessToken from the Collection and put it into a collection variable. Then one can access the collection variable using pm.collectionVariables.get("authToken")

Here is what needs to happen:

  1. In your Collection Variables tab, create a variable named accessToken without any value.
  2. In your Collection Scripts tab, create a Post-res script with this:
var authToken = pm.request.auth.oauth2.get("accessToken");
pm.collectionVariables.set("authToken", authToken);

This gets the oauth2 accessToken in the Collection and stores it in the authToken collection variable for later access!

Now one can access the authToken anywhere in the collection via pm.collectionVariables.get("authToken").

Thank you very much @kurtopel
this is exactly what i was looking for.

One addition to your answer:

  • there is no need to create a variable in first place, postman will create it automatically when it´s not existent
  • in your provided example, a variable “authToken” would be created, the variable “accessToken” is not used (probably typo in your answer).

The solution works for the token, that is being used in that request (accessToken), other tokens like the refreshToken cannot be extracted this way, i found.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.