You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Newman中传递凭据并设置accessToken?含Azure DevOps场景

问题描述

我在Postman集合的前置请求脚本中编写了获取Access Token的逻辑(脚本如下),通过Newman传递用户名、密码作为环境变量时,Access Token虽已生成但未成功设置到环境变量中,导致后续测试脚本执行失败。有人建议在Newman命令后添加--export-environment参数导出更新后的环境变量,但不清楚如何在Azure DevOps管道中运行该命令。

前置请求脚本:

const executedOnce = pm.environment.get('executedOnce');
if(executedOnce == 0)
{
    console.log("Getting Access Token");
    const tokenUrl = pm.environment.get('tokenUrl');
    const webApiClientId = pm.environment.get('webApiClientId');
    const scope = pm.environment.get('scope');
    const username = pm.environment.get('username'); 
    const password = pm.environment.get('password');  

    const getTokenRequest = {
        method: 'POST',
        url: tokenUrl,
        body: {
            mode: 'formdata',
            formdata:[
                {key: 'client_id', value: webApiClientId},
                {key: 'scope', value: scope},
                {key: 'grant_type', value: 'password'}, 
                {key: 'username', value: username},
                {key: 'password', value: password}
            ]
        }
    };

    pm.sendRequest(getTokenRequest, (err, response) => {
        const jsonResponse = response.json();
        const newAccessToken = jsonResponse.access_token;
        pm.environment.set('accessToken', newAccessToken);
        pm.environment.set('executedOnce', 1)
        console.log("Access Token Obtained");
    });
解决方法

1. Newman导出参数的作用

添加--export-environment localenvironment.json参数后,Newman会将运行过程中更新的环境变量(包括动态生成的accessToken)写入指定的环境文件,后续请求即可读取到最新的变量值。

2. Azure DevOps管道执行配置

步骤1:安装Node.js和Newman

在管道中先完成依赖安装,确保代理机器具备运行Newman的环境:

- task: NodeTool@0
  inputs:
    versionSpec: '18.x' # 选择适配业务的Node.js版本
  displayName: '安装Node.js'

- script: npm install -g newman
  displayName: '安装Newman'

步骤2:运行带导出参数的Newman命令

使用Script任务执行Newman命令,建议用Azure DevOps管道变量存储用户名、密码等敏感信息,避免明文暴露:

- script: |
    newman run testscripts_postman.json -e localenvironment.json --env-var "username=$(username)" --env-var "password=$(password)" --export-environment updated_environment.json
  displayName: '执行Postman集合测试'

说明:$(username)和$(password)是Azure DevOps管道中预先定义的变量;updated_environment.json为导出的更新后环境文件,也可直接覆盖原文件,但用新文件名能降低意外覆盖的风险。

步骤3:(可选)保存更新后的环境文件

若后续任务需要用到更新后的环境变量,可通过发布任务将文件保存为构建产物:

- task: PublishBuildArtifacts@1
  inputs:
    PathtoPublish: 'updated_environment.json'
    ArtifactName: 'postman-environment'
    publishLocation: 'Container'
  displayName: '发布更新后的环境文件'

内容的提问来源于stack exchange,提问作者Cherylaksh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 08:02:53