Reputation: 1
Im trying to start Azure VM programmatically (using management certificate). Im getting this error when trying to process http request: error 401 Unauthorized. (thats not an error that appears when certificate is wrong). Tried other request to the same subscription(list hosted services) - went ok, seems like the problem appears only when im tryin to work with virtual machines. Have no idea what am i doing wrong. Here's the code:
static void Main(string[] args)
{
Certificate = new X509Certificate2(Convert.FromBase64String(base64Cer));
string uriFormat = "https://management.azure.com/subscriptions/{my_sub_id}/resourceGroups/{my_resourse_group}/providers/Microsoft.ClassicCompute/virtualMachines/{my_machine_name}/start?api-version={0}";
Uri uri = new Uri(string.Format(uriFormat, Version));
XDocument responseBody;
HttpWebResponse response = InvokeRequest(uri, "POST", out responseBody);
HttpStatusCode statusCode = statusCode = response.StatusCode;
Console.WriteLine("The status of the operation: {0}\n\n", statusCode.ToString());
Console.WriteLine(responseBody.ToString(SaveOptions.OmitDuplicateNamespaces));
Console.Write("Press any key to continue:");
Console.ReadKey();
}
private static HttpWebResponse InvokeRequest( Uri uri, string method, out XDocument responseBody)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = method;
request.Headers.Add("x-ms-version", Version);
request.ClientCertificates.Add(Certificate);
request.ContentType = "application/json";
request.ContentLength = 0;
responseBody = null;
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = (HttpWebResponse)ex.Response;
}
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Ignore;
if (response.ContentLength > 0)
{
using (XmlReader reader = XmlReader.Create(response.GetResponseStream(), settings))
{
try
{
responseBody = XDocument.Load(reader);
}
catch
{
responseBody = null;
}
}
}
response.Close();
return response;
}
Upvotes: 0
Views: 644
Reputation: 136206
The reason you're getting this error is because you're trying to authenticate/authorize an Azure Resource Manager (ARM)
API request with an X509 Certificate. Authorization of ARM API requires Azure AD based authorization token
. Please see this link for authenticating/authorizing an ARM API request: https://msdn.microsoft.com/en-us/library/azure/dn790557.aspx.
X509 Certificate based authentication/authorization works only for Classic Service Management API requests.
Upvotes: 2