简体   繁体   中英

Adding Management Certificate programatically to Azure using Azure Rest API

IM trying to add a management certificate programmatically using Windows Azure Service Management REST API Reference

Below is the snippets used

public async void AddManagmentCertificate(string subscriptionId, string version)
        {
            string hittingurl = "https://management.core.windows.net/{0}/certificates";
            hittingurl = String.Format(hittingurl, "subidgoeshere");
            XmlDocument addcertDoc = await HelperMethods.PostXmlDocument(hittingurl,"2012-03-01");
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(addcertDoc.NameTable);
            nsmgr.AddNamespace("rest", xmlnamespace);
            if (addcertDoc != null)
            {
                XmlNodeList certadded = addcertDoc.SelectNodes("//rest:SubscriptionCertificateThumbprint", nsmgr);

                if (certadded.Count > 0)
                {
                    string thumbprint = certadded[0].InnerXml.ToString();
                    if (String.IsNullOrEmpty(thumbprint))
                    {

                    }
                    else
                    {
                        LoadData();
                    }
                }


            }



        }


 public static async Task<XmlDocument> PostXmlDocument(string hittingUrl,string Version)
        {
            HttpWebRequest request;
            XmlDocument responsebody = new XmlDocument();


            Uri uri = new Uri(hittingUrl);


            request = (HttpWebRequest)HttpWebRequest.Create(uri);

            request.Method = "POST";
            request.Headers.Add("x-ms-version", Version);
            string certpath = HttpContext.Current.Server.MapPath(@"Certificates\epgwin8dashboard.cloudapp.net.cer");

            request.ClientCertificates.Add(X509Certificate2.CreateFromCertFile(certpath));

            request.ContentType = "application/xml";
            request.ContentLength = 0;




            HttpWebResponse webresponse = null;

            try
            {

                webresponse = (HttpWebResponse)await request.GetResponseAsync();


            }
            catch (Exception)
            {

            }

            HttpStatusCode statuscode = webresponse.StatusCode;
            if (webresponse.ContentLength > 0)
            {
                using (XmlReader reader = XmlReader.Create(webresponse.GetResponseStream()))
                {
                    responsebody.Load(reader);


                }
            }

            if (statuscode.Equals(HttpStatusCode.OK))
            {

                return responsebody;

            }
            else
            {
                return null;
            }


        }

Please tell me what else need to be enhanced to make this working with out errors

I have being returned by 411 error.

Try this code. I created a simple console application for this.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

namespace StackOverflowAddManagementCertificate
{
    class Program
    {
        private static string requestPayloadFormat =
            @"<SubscriptionCertificate xmlns=""http://schemas.microsoft.com/windowsazure"">
                <SubscriptionCertificatePublicKey>{0}</SubscriptionCertificatePublicKey>
                <SubscriptionCertificateThumbprint>{1}</SubscriptionCertificateThumbprint>
                <SubscriptionCertificateData>{2}</SubscriptionCertificateData>
            </SubscriptionCertificate>";

        private static string subscriptionId = "your subscription id";

        private static string certificateThumbprint = "certificate thumbprint for validating service management API request";

        private static string x_ms_version = "2012-03-01";

        private static string certificateFile = @"full path of the certificate file which needs to be uploaded e.g. D:\mytest1.cer";
        static void Main(string[] args)
        {
            try
            {
                //First read the certificate from certificate store which will be used to authenticate the request.
                X509Store certificateStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                certificateStore.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection certificates = certificateStore.Certificates;
                var matchingCertificates = certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);
                var managementCert = matchingCertificates[0];

                X509Certificate2 cert = new X509Certificate2(certificateFile);
                var pk = Convert.ToBase64String(cert.GetPublicKey());
                var tp = cert.Thumbprint;
                var rawData = Convert.ToBase64String(cert.RawData);

                var requestBody = string.Format(CultureInfo.InvariantCulture, requestPayloadFormat, pk, tp, rawData);

                var requestBodyBytes = Encoding.UTF8.GetBytes(requestBody);

                string requestUrl = string.Format(CultureInfo.InvariantCulture,
                                                  "https://management.core.windows.net/{0}/certificates", subscriptionId);

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(requestUrl);
                req.Method = "POST";
                req.ContentType = "application/xml";
                req.ContentLength = requestBodyBytes.Length;
                req.Headers.Add("x-ms-version", x_ms_version);
                req.ClientCertificates.Add(managementCert);
                using (Stream s = req.GetRequestStream())
                {
                    s.Write(requestBodyBytes, 0, requestBodyBytes.Length);
                }
                using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
                {
                    var status = resp.StatusCode;
                }

            }
            catch (WebException webEx)
            {
                var resp = webEx.Response;
                using (var respStream = resp.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(respStream))
                    {
                        string s = sr.ReadToEnd();
                    }
                }

                throw;
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM