How to set basic authorization from environment variable in postman?

Arbaz.in picture Arbaz.in · Jul 4, 2019 · Viewed 7.8k times · Source

I want to set basic Authorization in Postman using environment variable. Because I have different authorization username and password for the different API calls.

I set my postman according to below:

In Authorization Tab: I've selected No Auth
In Header Tab: Key=Authorization Value= Basic{{MyAuthorization}}
In Body Tab:

{
    "UserName": "{{UserName}}",
    "ServiceUrl": "{{ServiceUrl}}"
}

//which set it from the envitonment variable

In Pre-request Tab:

// Require the crypto-js module
var CryptoJS = require("crypto-js");

// Parse the `username` and `password` environment variables
let credsParsed = CryptoJS.enc.Utf8.parse(`${pm.environment.get('admin')}:${pm.environment.get('admin')}`);

// Base64 encoded the parsed value
let credsEncoded = CryptoJS.enc.Base64.stringify(credsParsed);

// Set the valuse as an environment variable and use in the request
pm.environment.set('MyAuthorization', credsEncoded);
console.log(credsEncoded);

In Test Tab:

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("LoginInfoID", jsonData.First.LoginInfoID);

Then I've sent the request and got unauthorized.

After that, I've set auth type to basic auth with username and password it's working fine and I got what I wanted from the response.

Answer

bjones01001101 picture bjones01001101 · Jan 21, 2020

Another way which worked for me:

  1. Set up environment variables for 'username' and 'password', and save
  2. In the Authorization tab of the request, select Basic Auth
  3. In the Username field, enter {{username}}
  4. For the Password field, click "Show Password", and enter {{password}}

Hope this helps others :)