Changing Authorization Type with Environment Variable

Hello! I am in the process of setting up my Staging and Production Environments for my workspace. My APIs require different types of Authorization per environment.

Is there any way to dynamically change the Authorization Type for a collection based on the Environment selected?

My setup:
Staging environment I set setup a pre-request script to set headers for my entire collection and set my Authorization Type to “NO AUTH” since auth is passed in my headers/pre-request:

pm.request.headers.add({key: ‘header’, value: ‘token’ })
pm.request.headers.add({key: ‘header’, value: ‘token’ })

Production = When I swap environment to Production, I want the authorization type for my collection to change from “NO AUTH” to “BASIC AUTH” and then I would want to supply a set of username/password variables.

Hi @gpatrick! Welcome to the community :wave:

I understand you would like to dynamically change Auth type in the pre-request script.
Looking at the SDK doc, I wonder if you can use this method.

Please let me know how it goes :grinning:

Hi @gpatrick,

Welcome to the community! :clap:

I would agree with @taehoshino, as that can be a powerful method to change between authorization types.

However, since in essence, authorization are a function of http headers, your method should work just fine.

First, create an env variable that states the name of your environment (Prod, Staging, etc).

Then in your Pre-Request Script, use an if statement to check the value of the env variable:

if (pm.environment.get("env") == ("Prod") {
    pm.request.upsertHeader({"Authorization": "Basic bdasbdasgdas="})
}

(Reference to Postman SDK below)
https://www.postmanlabs.com/postman-collection/Request.html#upsertHeader

Then for very other request, since it doesnt require authorization, you simply omit the Authorization header.

Using this or @taehoshino’s way should work either way, though his is probably better :slight_smile:.

Best,
Orest