13

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

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

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

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

//which set it from the envitonment variable

在预请求选项卡中:

// 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);

在测试选项卡中:

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

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

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

4

2 回答 2

30

另一种对我有用的方法:

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

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

于 2020-01-21T17:09:17.367 回答
4

可以cryptp-jsPre-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);

您可以将您的凭据添加到一组不同的environment文件中,在密钥usernamepassword.

在请求中,只需设置Header如下:

邮差

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

这是您可以实现这一目标的一种方式,但也会有其他方式。

于 2019-07-04T09:39:54.533 回答