Freigeben über


Windows Azure adding multiple certificate to hosted service using powershell and C#

This article explains how to add multiple certificates to your Azure hosted service using C# or PowerShell. It also contains sample powershell code and C# code using REST API to do so.

 

Before you can use a Windows Azure service certificate, you must upload it to a hosted service. The following image shows the process of adding a new certificate to a subscription's certificate store. You can upload only one certificate at a time.

 

 

Also while creating please ensure clicking on "Include all certificates in certification path if possible" option. It will ensure that the entire certificate chain will be exported along with cert. With this subsequently when you will upload this certificate to Azure all the cert in certificate chain will be uploaded to Azure certificate store.

For a hosted service needing one or two certificate requirement this is a pretty simple process. But for hosted services needing high number of certificates it's a repetitive and time taking process as you can't upload more than one cert at a time (one reason for this limit is each cert file need a password). Further this complexity multiplies when you have to repeat this process multiple times during Dev or Test cycles.

For Azure automation I found PowerShell vary promising utility , you can use following script to add cert to your hosted service.

 


#Final Arun Rakwal

Add-PSsnapin AzureManagementToolsSnapin

Add-PsSnapin WAPPSCmdlets

#Add Subscription ID

$sub = '8a27c306-9434-4d59-971a-c3dc8223432'

#Add subscription management cert thumbprint

$cert = Get-Item cert:\LocalMachine\My\22598061DFB6543663E2D1A4C70045F52862342

$servicename='myservice'

# Certificate Name and password

$certfilename='D:\Work\cert\SSL_Cert1.pfx'

$certpwd='123'

#Find the hosted service where you want to add cert

$hostedService=Get-HostedService -serviceName $HostedServiceName -subscriptionId $subscriptionId -certificate $cert

Write-Host "Adding Certificate to Service"

# Add the certificate to the hosted service (doesn't matter it is there already)

$hostedService | Add-Certificate -CertificateToDeploy $certfilename -Password $certpwd

Remove-PSsnapin AzureManagementToolsSnapin

Remove-PSsnapin WAPPSCmdlets


 

It’s useful only limitation I found with this script is the Add-Certificate cmdlet would not upload full cert chain to Azure. At this point I explored REST APIs and found the way. I created a small windows form based utility to perform this job , here is code.


private static
X509Certificate2 GetCertificateFromStore(string thumbPrint)

                { 

                    // Get the certificatestore for the current user.

                    X509Store store = new X509Store(StoreLocation.LocalMachine );

                    try

                    {                       
store.Open(OpenFlags.ReadOnly);

                       
X509Certificate2Collection certCollection =store.Certificates.Find(X509FindType.FindByThumbprint,thumbPrint,false);

                        if(certCollection.Count == 0)

                            return null;

                        // Return the first certificate in the collection, has the right thumbPrint and is current.

                        return certCollection[0];

                    }

                    finally

                    {

                        store.Close();

                    } 

                } 

 

                private void btnAddCert_Click(object sender, EventArgs e)

                {

                    try

                    {

                        string applicationName= "hostedservice"; // Add your hostedservice name

                        X509Certificate2managementCertificate =GetCertificateFromStore("22598061DFB6543663E2D1A4C70045F528635A6F");

                        OpenFileDialog cerFile= new OpenFileDialog();

                        cerFile.Title ="Select Cert File (s).";

                        cerFile.Filter ="PFX Files|*.pfx";

                        cerFile.Multiselect =true;

                        if(cerFile.ShowDialog() == DialogResult.OK)

                        {                           

                            foreach (String pfxpath in cerFile.FileNames)

                            {

                                string password= txtCertPassword.Text;

                                // Constructthe request URI.  

                                var req =(HttpWebRequest)WebRequest.Create(string.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/certificates",txtSubsID.Text, applicationName));

                                // Set the request method and the content type for the request.

                                req.Method ="POST";

                                req.ContentType= "application/xml";

                                // Add thex-ms-version header.

                               
req.Headers.Add("x-ms-version", "2009-10-01");

                                // Add the certificate.

                               
req.ClientCertificates.Add(managementCertificate);

                                // Constructthe request body.

                                using (var writer = new StreamWriter(req.GetRequestStream()))

                                {                                   
writer.Write(string.Format(@"<?xmlversion=""1.0"" encoding=""utf-8""?>

                                          
<CertificateFile xmlns=""https://schemas.microsoft.com/windowsazure"">                                          
<Data>{0}</Data>                                          
<CertificateFormat>pfx</CertificateFormat>                                          
<Password>{1}</Password>                                          
</CertificateFile>",Convert.ToBase64String(File.ReadAllBytes(pfxpath)), password));

                                }

                                // Submit therequest and return the request ID.

                                String certresutl= req.GetResponse().Headers["x-ms-request-id"];

                               
MessageBox.Show("Uploaded cert "+pfxpath); 

                            }

                        }

                    }

                    catch (Exception ee)

                    {       

           MessageBox.Show(ee.ToString(),"AzureTookit");

                    }                }


 

I am sure you will find this article helpfull. Pleaes rate this article and share your feedback.

For more details please feel free to contact me at arunrakwal@yahoo.com.