【问题标题】:Get Azure REST access token in Postman pre-request script在 Postman 预请求脚本中获取 Azure REST 访问令牌
【发布时间】:2020-06-29 14:09:41
【问题描述】:

有谁知道在 Postman 预请求脚本中获取 Azure 访问令牌的最佳方法是什么?尝试获取当前登录用户的令牌,而无需创建服务主体,这在 How to Call the Azure REST APIs with Postman In No Time Flat 中进行了描述。

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

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'。截图如下:

【问题讨论】:

标签: javascript azure postman azure-managed-identity azure-node-sdk


【解决方案1】:

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

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

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

注意:

  1. 由于安全问题,不推荐使用ROPC流程,需要在postman中暴露用户名和密码,如果你的用户账户启用了MFA,它将无法工作。

  2. 要使用此流程,您还需要一个 AD 应用程序(应用程序注册),如果您没有创建权限,解决方法是使用 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

注意clientId1950a258-227b-4e31-a9cf-717495945fc2,即微软应用Microsoft Azure PowerShellclientId,请勿更改。

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

【讨论】:

  • 感谢您的回复@Joy,这是有用的信息。但不幸的是没有帮助,因为我打开了 MFA。在 C# 控制台应用程序上,我们可以做 var token = new AzureServiceTokenProvider().GetAccessTokenAsync("https://management.azure.com/") 我们不能在 JS 中做类似的事情吗?仅供参考,我有一个 C# 控制台应用程序,它可以在我的本地计算机上运行。
  • @dushyantp 1.在这种情况下,我的解决方案是唯一的方法。如果您的帐户启用了 MFA,则无法在邮递员中获取令牌,因为它不允许交互式登录。 2.这完全是另一个问题,恐怕你需要在另一个帖子中问。
猜你喜欢
  • 2018-04-26
  • 2022-01-05
  • 2021-07-04
  • 2018-09-30
  • 2020-07-05
  • 2018-08-31
  • 2018-08-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多