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.
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.
*** 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.
Another way which worked for me:
Hope this helps others :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With