使用Powershell的Azure API Management Report API

时间:2017-11-08 05:15:09

标签: powershell azure azure-api-management

我正在尝试使用Powershell执行APIM Report API,但它不起作用。

这是powershell代码。

$gen_sas_code = @"
using System;   
using System.Text;   
using System.Globalization;   
using System.Security.Cryptography;   

public class Sas  
{   
public static void GenSas()   
{   
    var id = "integration";   
    var key = "myprimarykey";   
    var expiry = DateTime.UtcNow.AddDays(10);   
    using (var encoder = new HMACSHA512(Encoding.UTF8.GetBytes(key)))   
    {   
        var dataToSign = id + "\n" + expiry.ToString("O", CultureInfo.InvariantCulture);   
        var hash = encoder.ComputeHash(Encoding.UTF8.GetBytes(dataToSign));   
        var signature = Convert.ToBase64String(hash);   
        var encodedToken = string.Format("SharedAccessSignature uid={0}&ex={1:o}&sn={2}", id, expiry, signature);   
        Console.WriteLine(encodedToken);   
    }   
}   
}
"@

Add-Type -TypeDefinition $gen_sas_code -Language CSharp

$sas = [Sas]::GenSas()

$interval = "PT15M"
$start_time = "'2017-10-16T04:02:00'"
$end_time = "'2017-10-16T04:15:00'"
$report_url = "https://myapim.management.azure-api.net/reports/byTime?api-version=2017-03-01&interval=$interval&`$filter=timestamp+ge+datetime$start_time+and++timestamp+le+datetime$end_time"
$report_headers = @{ "Authorization" = "$sas" };

Invoke-RestMethod -Method Get -Uri $report_url -Headers $report_headers

我在此文档中提到了报告API(https://docs.microsoft.com/en-us/rest/api/apimanagement/apimanagementrest/azure-api-management-rest-api-report-entity#ReportByTime)。

这是错误回复。

*远程服务器返回错误:(401)Unzuthorized

Invoke-RestMethod : リモート サーバーがエラーを返しました: (401) 許可されていません*
発生場所 C:\sas.ps1:56 文字:1
+ Invoke-RestMethod -Method Get -Uri $report_url -Headers $report_headers
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod]、WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

所以,我认为powershell代码存在一些问题,因为我已经确认通过使用curl命令执行Report API,上面代码生成的SAS可以正常工作。

你有什么想法吗?