-1

我正在尝试编写一个本地控制台应用程序,它将使用Azure REST API交换一个 Azure Web App 插槽。使用以下代码,我得到 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 进行身份验证的应用程序。这将是一个具有匿名身份验证的可公开访问的 Web 应用程序。

4

2 回答 2

0

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

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);
} 
于 2017-12-28T10:54:17.247 回答
0

一般来说,您需要使用 Auth 令牌将 Authorization 标头附加到请求中。有多种获取方式,请参阅此链接

于 2017-12-28T10:12:58.753 回答