Created
November 29, 2017 17:19
-
-
Save kevinhillinger/856a35f6b64feda3d2143eb71e70d1f5 to your computer and use it in GitHub Desktop.
Get SharedAccessSignature for API Management (v1 REST API) using PowerShell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$Source = @" | |
namespace Microsoft.Apim | |
{ | |
using System; | |
using System.Net; | |
using System.Text; | |
using System.Globalization; | |
using System.Security.Cryptography; | |
public static class Tools | |
{ | |
public static string GetSharedAccessSignature(string id, string key) | |
{ | |
DateTime then = DateTime.UtcNow.AddMinutes(10); | |
// seconds must be zero for this to work | |
DateTime expiry = new DateTime(then.Year, then.Month, then.Day, then.Hour, then.Minute, 0, DateTimeKind.Utc); | |
using (HMACSHA512 hmac = new HMACSHA512(Encoding.UTF8.GetBytes(key))) | |
{ | |
string dataToSign = id + "\n" + expiry.ToString("O", CultureInfo.InvariantCulture); | |
byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(dataToSign)); | |
string signature = Convert.ToBase64String(hash); | |
return string.Format("SharedAccessSignature {0}&{1:yyyyMMddHHmm}&{2}", id, expiry, signature); | |
} | |
} | |
} | |
} | |
"@ | |
Add-Type -TypeDefinition $Source -Language CSharp | |
if ($(Get-AzureRmContext) -eq $null) { | |
Login-AzureRmAccount | |
} | |
$apimContext = New-AzureRmApiManagementContext -ResourceGroupName "<resource group name>" -ServiceName "<service name>" | |
$access = Get-AzureRmApiManagementTenantAccess -Context $apimContext | |
$id = $access.Id | |
$key = $access.PrimaryKey | |
$token = [Microsoft.Apim.Tools]::GetSharedAccessSignature($id, $key) | |
$token | |
$contentType = "application/json" | |
$headers = @{ | |
"Authorization" = $token; | |
"Content-Type" = $contentType; # tell APIM we're using a swagger definition | |
"If-Match" = "*"; # allows us to overwrite the existing API definition in APIM | |
} | |
$uri = "https://$($apimContext.ServiceName).management.azure-api.net/apis?api-version=2017-03-01" | |
Write-Output "Getting list of apis from '$uri' `n" | |
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 #force TLS 1.2 | |
$response = Invoke-RestMethod -Uri $uri -Headers $headers -ContentType $contentType -Method Get | |
$response.Value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment