如何从邮递员中的环境变量设置基本授权?

Arb*_*.in 10 postman postman-pre-request-script

我想使用环境变量在 Postman 中设置基本授权。因为我对不同的 API 调用有不同的授权用户名和密码。

我根据以下设置我的邮递员:

在授权选项卡中:我
在标题选项卡中选择了无身份验证:键=Authorization值=Basic{{MyAuthorization}}
在正文选项卡中:

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

//which set it from the envitonment variable
Run Code Online (Sandbox Code Playgroud)

在预请求选项卡中:

// 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);
Run Code Online (Sandbox Code Playgroud)

在测试选项卡中:

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("LoginInfoID", jsonData.First.LoginInfoID);
Run Code Online (Sandbox Code Playgroud)

然后我发送了请求并获得了未经授权的授权。

之后,我使用用户名和密码将身份验证类型设置为基本身份验证,它工作正常,我从响应中得到了我想要的。

bjo*_*101 23

另一种对我有用的方法:

  1. 为“用户名”和“密码”设置环境变量,并保存
  2. 在请求的授权选项卡中,选择基本身份验证
  3. 在用户名字段中,输入 {{username}}
  4. 对于密码字段,单击“显示密码”,然后输入 {{password}}

希望这对其他人有帮助:)

  • 这就是答案 (2认同)

Dan*_*ton 5

可以使用cryptp-js一个Pre-request Script非常粗略的解决方案,如下所示:

// 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('username')}:${pm.environment.get('password')}`);

// 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('authCreds', credsEncoded);
Run Code Online (Sandbox Code Playgroud)

您可以将凭据添加到environment密钥username和下的一组不同文件中password

在请求中,只需Header这样设置:

邮差

您还可以在集合/子文件夹级别设置这些内容,这样您就不会在每个请求中重复自己。

这是实现这一目标的一种方法,但也有其他方法。