Reputation: 177
I'm trying to execute APIM Report API using Powershell but it doesn't works.
Here's powershell code.
$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
I referred this document about report API (https://learn.microsoft.com/en-us/rest/api/apimanagement/apimanagementrest/azure-api-management-rest-api-report-entity#ReportByTime).
Here's error response.
*The remote server returned error: (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
So, I consider that the powershell code has some problems because I have already confirmed that the SAS which is generated by above code works correctly by executing Report API using curl command.
Do you have any ideas?
Upvotes: 0
Views: 400
Reputation: 1090
It's a slightly annoying issue, but it comes down to newline handling in Powershell, the \n
in the .net
sample is referring to a newline, so you have to use the native way PowerShell declares a newline with a backtick instead, so do this:
var dataToSign = id + "`n" + expiry.ToString("O", CultureInfo.InvariantCulture);
... instead of:
var dataToSign = id + "\n" + expiry.ToString("O", CultureInfo.InvariantCulture);
Upvotes: 0
Reputation: 679
Try using this script to generate the token https://github.com/Azure/api-management-samples/blob/master/scripts/Get_AzureRmApiManagementManagementToken.ps1
Upvotes: -1