Search code examples
c#restazureazure-active-directoryazure-deployment-slots

Authorizing an Azure REST API Request


I am trying to write a local console application which will swap an Azure Web App slot using the Azure REST API. Using the following code I get a 401 (Unauthorized) response:

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);
} 

I know I need to put in some kind of credentials but what I have found seems to apply to apps using Azure AD for authentication. This will be a publicly accessible web app with anonymous authentication.


Solution

  • Generally speaking you need to attach a Authorization header to the request with the Auth token. There are numerous ways of getting it, see this link or this.