Azure虚拟机和REST API存在问题

时间:2016-06-01 13:36:10

标签: rest azure authentication virtual-machine

我尝试以编程方式启动Azure VM(使用管理证书)。我在尝试处理http请求时收到此错误:错误401未经授权。 (这不是证书错误时出现的错误)。尝试了对同一订阅的其他请求(列出托管服务) - 好了,好像只有在我尝试使用虚拟机时才出现问题。不知道我做错了什么。这是代码:

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

1 个答案:

答案 0 :(得分:2)

您收到此错误的原因是您尝试使用X509证书对Azure Resource Manager (ARM) API请求进行身份验证/授权。 ARM API的授权需要Azure AD based authorization token。请参阅此链接以验证/授权ARM API请求:https://msdn.microsoft.com/en-us/library/azure/dn790557.aspx

X509基于证书的身份验证/授权仅适用于Classic Service Management API请求。