Reputation: 545
I've read other similar answers but they either use IIS, talk about self-signed certificates or don't fill the purpose at all.
I'm trying to create a simple web API that will be hosted in a Windows machine with SQL Express using .NET 5.
I'm able to create a self-signed certificate and use that during development, but this will be hosted in a client's machine and they probably have a SSL certificate. In the past, with web applications that run only in localhost I did something like this:
public static IHostBuilder CreateHostBuilder ( string [] args ) =>
Host.CreateDefaultBuilder( args )
.ConfigureWebHostDefaults( builder =>
{
builder.UseStartup<Startup>();
builder.UseKestrel(options => {
if ( ServerConfiguration.ShouldUseHttps() )
{
options.Listen( IPAddress.Any, 6050, listenOptions =>
{
listenOptions.UseHttps( Path.Combine( "Certificates", "cert.pfx" ), CertificatePassword );
} );
}
else
{
options.Listen( IPAddress.Any, 6050 );
}
} );
} );
Where cert.pfx is my self-signed certificate. I would ship that certificate with the software, and tell the client to install it, then they can use HTTPS and the browser would trust the certificate. Probably enough for a localhost application, but not for an exposed API.
So let's say the client has bought an SSL certificate and I want my .NET application to use that certificate, that will be installed on the same machine as my application. How can I accomplish that?
Right now, I've just deployed my application in another computer, without any certificates or anything else, but of course I get errors of type "The SSL certificate can't be trusted" (in postman for example).
If the client doesn't buy an SSL certificate, can we use a self-signed certificate?
Thank you very much.
Upvotes: 1
Views: 1747
Reputation: 40928
Don't configure your endpoints in code. Instead, configure them in your appsettings.json file, as described in the Kestrel documentation. You can configure just one endpoint, or multiple.
Here's an example configuration that has an HTTP and HTTPS endpoint, with the certificate from a pfx file with a password:
{
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://localhost:5000"
},
"HttpsInlineCertFile": {
"Url": "https://localhost:5001",
"Certificate": {
"Path": "<path to .pfx file>",
"Password": "<certificate password>"
}
}
}
}
}
The documentation shows different configurations for the certificate, like a .pem and key file (like you get from Let's Encrypt, for example) or using the Windows certificate store.
This way, if the client gets their own cert, it's just a matter of updating the appsettings.json.
Upvotes: 2