授权 Azure REST API 请求

Authorizing an Azure REST API Request

我正在尝试编写一个本地控制台应用程序,它将使用 Azure REST API 交换 Azure Web 应用程序插槽。使用以下代码,我得到 401(未经授权)响应:

public async Task Swap(string subscription, string resourceGroup, string site, string slot) 
{
    var client = new HttpClient();

    var url =
        $"https://management.azure.com/subscriptions/{subscription}/resourceGroups/{resourceGroup}/providers/Microsoft.Web/sites/{site}/applySlotConfig?api-version=2016-08-01";

    var data = new {preserveVnet = true, targetSlot = slot};

    var message = new HttpRequestMessage
    {
        RequestUri = new Uri(url),
        Method = HttpMethod.Post,
        Content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json")
    };

    var response = await client.SendAsync(message);

    Console.WriteLine(response.StatusCode);
} 

我知道我需要输入某种凭据,但我发现似乎适用于使用 Azure AD 进行身份验证的应用程序。这将是一个具有匿名身份验证的可公开访问的网络应用程序。

一般来说,您需要使用授权令牌将授权 header 附加到请求中。有很多方法可以得到它,看这个 link or this.

这是我设法做到的(使用提供的链接):

private async Task<string> GetAccessToken(string tenantName, string clientId, string clientSecret)
{
    var authString = "https://login.microsoftonline.com/" + tenantName;
    var resourceUrl = "https://management.azure.com/";

    var authenticationContext = new AuthenticationContext(authString, false);
    var clientCred = new ClientCredential(clientId, clientSecret);
    var authenticationResult = await authenticationContext.AcquireTokenAsync(resourceUrl, clientCred);
    var token = authenticationResult.AccessToken;

    return token;
}

然后在我之前的方法中:

public async Task Swap(string subscription, string resourceGroup, string site, string slot) 
{
    var client = new HttpClient();

    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await GetAccessToken("XXX", "XXX", "XXX"));

    var url =
            $"https://management.azure.com/subscriptions/{subscription}/resourceGroups/{resourceGroup}/providers/Microsoft.Web/sites/{site}/applySlotConfig?api-version=2016-08-01";

    var data = new {preserveVnet = true, targetSlot = slot};

    var message = new HttpRequestMessage
    {
        RequestUri = new Uri(url),
        Method = HttpMethod.Post,
        Content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json")
    };

    var response = await client.SendAsync(message);

    Console.WriteLine(response.StatusCode);
}