首页 > 解决方案 > 如何使用 GET 请求查询 management.azure.com?

问题描述

我曾经使用公共 API 格式来使用 AppId 和 ApiKey 进行身份验证。

最近,我必须通过 Azure Active Directory 进行身份验证才能查询 Application Insights。

据我了解当我使用 Azure Active Directory 时,我必须使用management.azure.com. 根据我从中学到的知识,需要编写一个链接:

https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{componentName}/query/query?api-version={apiVersion}&query={newQuery}

如果我理解正确,那么奇怪的/query/query部分就是我应该如何解释/{area}/[path]

我的查询看起来像这样:

requests
| where name =~ '{itemName}'
| where timestamp > datetime('{referenceDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff")}')
| project timestamp, id, name, success, customDimensions
| order by timestamp desc
| take 5

我确实删除了换行符:-)

我这样调用 API:

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

    var response = client.GetAsync(url).Result;

但是我收到了错误的请求。

我需要使用 AAD 身份验证获取查询 Application Insights(我已经解决了,因为没有使用 Auth 的行或错误的值我得到未经授权)。在 Azure Active Directory 中注册应用程序时,除了 Data.Read 之外,我没有获得任何添加权限的选项 - 当使用 Post(与提供的代码不同)时,我确实得到了“不允许的方法”。

请指教。

编辑

我尝试在 Postman 中运行相同的查询。

{
  "error": {
    "message": "The request had some invalid properties",
    "code": "BadArgumentError",
    "innererror": {
        "code": "SemanticError",
        "message": "A semantic error occurred.",
        "innererror": {
            "code": "SEM0100",
            "message": "'' operator: Failed to resolve table or column or scalar expression named 'requests'"
        }
    }
  }
}

即使我将query参数缩短为requests. 所以我想我不知道如何在 GET API 调用中传递查询。

标签: c#azureazure-active-directoryazure-application-insights

解决方案


首先,API 格式应该如下所示,不是您问题中的格式,可以在此链接的 powershell 脚本中找到。

GET https://management.azure.com/subscriptions/<subscription-id>/resourcegroups/<resource-group-name>/providers/microsoft.insights/components/<appinsight-name>/api/query?api-version=2014-12-01-preview&query=requests|where timestamp > ago(24h)|count

实际上,如果你想用 Azure AD Authentication 调用这个 API,我能找到的最好的方法是使用Microsoft.Azure.Services.AppAuthentication库,不需要创建 AD 应用程序,只需使用下面的代码获取访问令牌,然后使用令牌调用API。

注意:运行代码时,请确保登录 Visual Studio 的用户帐户是订阅或 App Insight 中的RBAC 角色(例如Owner/ Contributor)。如果没有,请按照此链接授予访问权限。

static void Main(string[] args)
    {
        AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
        string accessToken = azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/").Result;
        Console.WriteLine(accessToken);
    }

我在邮递员中测试了令牌,它工作正常,您也可以在代码中使用它。

在此处输入图像描述


推荐阅读