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

如何在Postman预请求脚本中获取Azure访问令牌(无需服务主体)

在Postman预请求脚本中获取当前用户Azure访问令牌的正确方法

首先得说清楚你为啥会遇到那个错误:你用的ms-rest-azure是Node.js环境下的npm包,但Postman的预请求脚本跑在一个受限的沙箱里,根本没法直接引入外部包,所以才会报Cannot find module 'ms-rest-azure'的错。下面给你两种不用服务主体、直接获取当前登录用户令牌的可行方案:

方法一:用Postman内置的OAuth2功能(最省心)

这种方法不需要写复杂脚本,先手动完成一次登录,后续还能自动刷新令牌:

  1. 打开你的Postman请求,切换到Authorization标签页
  2. 认证类型选OAuth 2.0,然后点击Configure New Token
  3. 在弹出的配置面板里填这些信息:
    • Token Name:随便起个好记的名字,比如「Azure用户令牌」
    • Grant Type:选Authorization Code(这是获取用户令牌的标准流程)
    • Callback URL:直接填https://oauth.pstmn.io/v1/callback(Postman默认的回调地址)
    • Auth URL:https://login.microsoftonline.com/{你的租户ID}/oauth2/v2.0/authorize(租户ID可以填common、organizations,或者你具体的租户GUID)
    • Access Token URL:https://login.microsoftonline.com/{你的租户ID}/oauth2/v2.0/token
    • Client ID:去Azure AD注册一个应用,拿到它的Client ID(记得把Postman的回调地址加到应用的重定向URI里,还要把应用设为公共客户端)
    • Scope:填你需要的权限,比如https://management.azure.com/user_impersonation offline_access(加offline_access是为了拿到刷新令牌,方便后续自动续期)
  4. 点Get New Access Token,会弹出登录窗口,用你的Azure账号登录授权,之后Postman就会拿到令牌,点Use Token就能自动把令牌加到请求头里

如果想在预请求脚本里自动检查令牌是否过期并刷新,就加这段代码:

// 检查令牌是否过期
if (pm.globals.get("access_token_expiry") && Date.now() >= pm.globals.get("access_token_expiry")) {
    pm.sendRequest({
        url: "https://login.microsoftonline.com/{你的租户ID}/oauth2/v2.0/token",
        method: "POST",
        header: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: {
            mode: "urlencoded",
            urlencoded: [
                { key: "grant_type", value: "refresh_token" },
                { key: "client_id", value: "{你的客户端ID}" },
                { key: "refresh_token", value: pm.globals.get("refresh_token") },
                { key: "scope", value: "https://management.azure.com/user_impersonation offline_access" }
            ]
        }
    }, function (err, res) {
        if (err) {
            console.error("刷新令牌失败:", err);
        } else {
            var tokenData = res.json();
            pm.globals.set("access_token", tokenData.access_token);
            pm.globals.set("access_token_expiry", Date.now() + (tokenData.expires_in * 1000));
            pm.globals.set("refresh_token", tokenData.refresh_token);
        }
    });
}

方法二:手动在预请求脚本里调用微软身份端点

如果不想用Postman内置的OAuth2配置,也可以手动处理授权码流程:

  1. 先手动获取授权码:在浏览器里打开这个URL,登录后从回调地址的URL里拿到code参数
    https://login.microsoftonline.com/{你的租户ID}/oauth2/v2.0/authorize?client_id={你的客户端ID}&response_type=code&redirect_uri=https://oauth.pstmn.io/v1/callback&response_mode=query&scope=https://management.azure.com/user_impersonation offline_access
    
  2. 把这段代码放到预请求脚本里,替换掉占位符,就能交换到令牌:
pm.sendRequest({
    url: "https://login.microsoftonline.com/{你的租户ID}/oauth2/v2.0/token",
    method: "POST",
    header: {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    body: {
        mode: "urlencoded",
        urlencoded: [
            { key: "grant_type", value: "authorization_code" },
            { key: "client_id", value: "{你的客户端ID}" },
            { key: "code", value: "{你拿到的授权码}" },
            { key: "redirect_uri", value: "https://oauth.pstmn.io/v1/callback" },
            { key: "scope", value: "https://management.azure.com/user_impersonation offline_access" }
        ]
    }
}, function (err, res) {
    if (err) {
        console.error("获取令牌失败:", err);
    } else {
        var tokenData = res.json();
        pm.globals.set("access_token", tokenData.access_token);
        pm.globals.set("refresh_token", tokenData.refresh_token);
        pm.globals.set("access_token_expiry", Date.now() + (tokenData.expires_in * 1000));
        console.log("令牌已成功保存到全局变量");
    }
});

注意事项

  • 一定要在Azure AD里注册应用,并且把https://oauth.pstmn.io/v1/callback加到应用的重定向URI列表里
  • 给应用添加对应的API权限(比如Azure管理API的user_impersonation),并且确保是用户同意类型的权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 10:12:47