0

有谁知道在 Postman 预请求脚本中获取 Azure 访问令牌的最佳方法是什么?尝试获取当前登录用户的令牌而无需创建服务主体,这在如何使用 Postman 立即调用 Azure REST API 中进行了描述。

我在预请求脚本中尝试过:

var msRestAzure = require('ms-rest-azure');
function getAccessToken(){
    return msRestAzure.loginWithAppServiceMSI({resource: 'https://management.azure.com/'});
}
pm.globals.set("access_token", getAccessToken());

但它不断抛出错误:There was an error in evaluating the Pre-request Script: Error: Cannot find module 'ms-rest-azure'. 截图如下: 在此处输入图像描述

4

1 回答 1

1

需要在loginWithAppServiceMSIapp服务中使用,会使用app服务的Managed Identity来获取token,在Postman预请求脚本中,不支持使用。

我的访问权限受到限制,无法创建具有所需访问权限的服务主体。想用我的凭据在本地进行测试。

在这种情况下,如果您想使用您的用户凭据在预请求脚本中获取令牌,您可以选择使用Azure AD ROPC 流

笔记:

  1. 由于安全问题,不推荐使用ROPC流程,您需要在邮递员中公开用户名和密码,如果您的用户帐户启用了MFA,它将无法正常工作。

  2. 要使用此流程,您还需要一个 AD App(应用注册),如果您没有创建权限,解决方法是使用 Microsoft 内置应用程序,例如 Microsoft Azure PowerShell,您可以使用这种方式有一个测试,但我不建议你在生产环境中使用它。


请按照以下步骤操作:

1.更改邮递员集合中的预请求脚本,如下所示。

pm.sendRequest({
    url: 'https://login.microsoftonline.com/' + pm.variables.get("tenantId") + '/oauth2/token',
    method: 'POST',
    header: 'Content-Type: application/x-www-form-urlencoded',
    body: {
        mode: 'urlencoded',
        urlencoded: [ 
            {key: "grant_type", value: "password", disabled: false},
            {key: "client_id", value: pm.variables.get("clientId"), disabled: false},
            {key: "username", value: pm.variables.get("username"), disabled: false},
            {key: "resource", value: pm.variables.get("resource"), disabled: false},
            {key: "password", value: pm.variables.get("password"), disabled: false}
        ]
    }
}, function (err, res) {
    pm.globals.set("bearerToken", res.json().access_token);
});

2.使用如下变量。

clientId
resource
subscriptionId
tenantId
username
password

注意clientIdis1950a258-227b-4e31-a9cf-717495945fc2clientIdMicrosoft Application 的Microsoft Azure PowerShell,请勿更改。

在此处输入图像描述

3.其他设置和你提供的博客一样,然后发送请求获取资源组,在我这边可以正常工作。

在此处输入图像描述

于 2020-06-30T07:42:34.413 回答