Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Install SSL certificate programmatically using Microsoft.Web.Administration

Tags:

c#

iis

ssl

So the Microsoft.Web.Administration API is very easy to use to create HTTP and HTTPS bindings for sites:

using (ServerManager manager = new ServerManager())
{
    Site site = manager.Sites[siteName];
    site.Bindings.Clear();
    site.Bindings.Add("*:80:", "http");
    site.Bindings.Add("*:443:", "https");

    manager.CommitChanges();
}

But the HTTPS binding is pretty meaningless without the SSL certificate. How can I go about programatically choosing a cert file and using it with the HTTPS binding, using this API?

like image 857
dreadwail Avatar asked Feb 22 '11 20:02

dreadwail


People also ask

How do I install SSL certificate on my web hosting account?

Under Install and Manage SSL for your site (HTTPS), click Manage SSL Sites. Scroll down to the Install an SSL Website and click Browse Certificates. Select the certificate that you want to activate and click Use Certificate. This will auto-fill the fields for the certificate.

How do I bind an SSL certificate in Microsoft IIS?

Create an SSL Binding Click Add... to add your new SSL binding to the site. The default settings for a new binding are set to HTTP on port 80. Select https in the Type drop-down list. Select the self-signed certificate you created in the previous section from the SSL Certificate drop-down list and then click OK.


2 Answers

I feel like it's important to highlight Devator's comment in this answer. There appears to be a bug that prevents the certificate changes from taking place and I would never have solved it without seeing this comment.

If you set the binding information to itself, this causes IIS to bind the certificate. A quick example is shown below:

binding.BindingInformation = binding.BindingInformation;

like image 65
Murphybro2 Avatar answered Oct 11 '22 02:10

Murphybro2


The namespace doesn't contain an API for this, so you have to use its ConfigurationMethod to invoke an extension to the Win API that performs this function. Something like:

string certificateHash = <hash>
string certificateStore = <storename>  #my, localmachine, etc

ConfigurationMethod method = binding.Methods["AddSslCertificate"];
ConfigurationMethodInstance mi = method.CreateInstance();
mi.Input.SetAttributeValue("certificateHash", certificateHash);
mi.Input.SetAttributeValue("certificateStoreName", certificateStore);
mi.Execute();
like image 32
Taylor Bird Avatar answered Oct 11 '22 01:10

Taylor Bird