Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set basic authorization from environment variable in postman?

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.

like image 554
Arbaz.in Avatar asked Jul 04 '19 08:07

Arbaz.in


People also ask

How do I set authorization basic in Postman?

Basic authentication involves sending a verified username and password with your request. In the request Authorization tab, select Basic Auth from the Type dropdown list. Enter your API username and password in the Username and Password fields. For additional security, store these in variables.

What encoding does Postman use for basic auth?

*** If you remember what we learned in the last section, a basic access authentication requires a username and password to be encoded in Base64 but here we just sent the username and password in plain text.


1 Answers

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 :)

like image 59
bjones01001101 Avatar answered Oct 09 '22 22:10

bjones01001101