Pm.request manipulation not working before the request is sent

Hi, Postman Community!

Is it possible to use the pm.request.auth property or the pm.request.authorizeUsing() function, so I can handle authorization for requests in a pre-request script?

I tried to set the property like the following:

// either this object
const authz = {
  type: 'bearer',
  bearer: [
    {
      type: 'any',
      value: [
        {
          type: 'any',
          value: 'token value',
          key: 'token',
        },
      ],
      key: 'bearer',
    },
  ],
};

// or this another object
const authz = {
  type: 'bearer',
  bearer: [
    {
      type: 'any',
      value: 'token value',
      key: 'token',
    },
  ],
};

// either this way
pm.request.auth = authz;

// either this another way
pm.request.authorizeUsing(authz);

but none of them worked.

For the next examples, I had to setup the request Auth tab with type Bearer and a token generated previously, as I could not get the examples above to work.

Debugging the request, seems like I can only access and manipulate the auth property and the Authorization header after the request is sent.

The pre-request script for the request is:

// stage 1: the initial state of the request
console.log("request before")
console.log(pm.request.toJSON())

// stage 2: removing auth header and auth property
// from the request
pm.request.removeHeader('Authorization')
pm.request.auth = null

// stage 3: request after change; same result,
// except for the new property auth
console.log("request after")
console.log(pm.request.toJSON())

The post-response script for the request is:

// stage 4: request was sent already;
// but auth header is present and auth property is defined
console.log("response before")
console.log(pm.request.toJSON())

// stage 5: removing auth header and auth property
// again from the request
pm.request.removeHeader('Authorization')
pm.request.auth = null

// stage 6: auth header removed and auth property null
console.log("response after")
console.log(pm.request.toJSON())

The results for the scripts above is showed in the image below.

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