unosquare / embedio

A tiny, cross-platform, module based web server for .NET
http://unosquare.github.io/embedio
Other
1.46k stars 176 forks source link

Need help with setting up HTTPS server #520

Closed craftersmine closed 3 years ago

craftersmine commented 3 years ago

Hello everyone, I need help with setting up HTTPS server at localhost for tests. I have certificate as file, I loading it from file using X509Certificate2 and passing in WebServer options through "WithCertificate", but when I launch server I can't connect to it, browser just says "ERR_CONNECTION_CLOSED" or "ERR_CONNECTION_REFUSED". Certificate subject is localhost. What am I doing wrong?

That's how I initialize WebServer

var cert = X509Certificate.CreateFromSignedFile(fullpath)
webServer = new WebServer(o => o
                        .WithUrlPrefix("http://localhost:17001/")
                        .WithUrlPrefix("https://localhost:17002/") 
                        .WithMode(HttpListenerMode.EmbedIO) 
                        .WithCertificate(cert));

Even when I use http://localhost:80 and 443 at the same time HTTP version can be accessed, but HTTPS returns "ERR_CLOSED" or "ERR_REFUSED"

Thanks

craftersmine commented 3 years ago

So, I managed to run server with https. In order to use HTTPS, you need to actually use PFX file with certificate and private key Here you can read about how to create certificate for localhost: https://gist.github.com/cecilemuller/9492b848eb8fe46d462abeb26656c4f8 Then, you need to export key into PFX, I used openssl through WSL. If you created your certificate through openssl by using guide above, you need to run this command: "openssl pkcs12 -export -name "Test Certificate" -out localhost.pfx -inkey localhost.key -in localhost.crt" in order to export PFX. It will ask about export password, REMEMBER IT, it will be used when loading PFX! Then you need to create your server, you can use both HTTP and HTTPS:

var cert = new X509Certificate2(new X509Certificate("your-certificate.pfx", "PFX_EXPORT_PASSWORD"));
var webServer = new WebServer(o => o
                        //.WithUrlPrefix("http://localhost:80/") - uncomment if you want to use both HTTP and HTTPS
                        .WithUrlPrefix("https://localhost:443/") 
                        .WithMode(HttpListenerMode.EmbedIO) 
                        .WithCertificate(cert));

Now we can run server and get that green lock in our address bar in browser! But if you wanna use other port for HTTPS, you can, but you can't access server in app, which will use default 443 port, like browsers. Only clients with the same port as your server.