How to configure .NET Core API to use self-signed certificate

Alex Maher
2 min readJan 6, 2023

To generate self-signed certificates for a .NET Core API, you can use the following steps:

If you don’t already have, install OpenSSL on your system. You can download and install the OpenSSL binaries from the following URL: https://slproweb.com/products/Win32OpenSSL.html

Open a terminal window and navigate to the directory where you want to generate the certificate.

Run the following command to generate the private key for the certificate:

openssl genrsa -out mycert.key 2048

Run the following command to generate a certificate signing request (CSR):

openssl req -new -key mycert.key -out mycert.csr

This will prompt you to enter information about the certificate, such as the common name (e.g., the domain name of the API).

Run the following command to generate the self-signed certificate using the private key and CSR:

openssl x509 -req -days 365 -in mycert.csr -signkey mycert.key -out mycert.crt

The self-signed certificate is now stored in the mycert.crt file.

Here is an example of how you can configure SSL/TLS for your .NET Core API using the self-signed certificate:

In your Startup.cs file, add the following code to the ConfigureServices method:

services.AddHttpsRedirection(options =>
{
options.HttpsPort = 5001;
options.ClientCertificateMode = ClientCertificateMode.AllowCertificate;
options.ServerCertificate = new X509Certificate2("mycert.crt");
});

This will configure the API to redirect HTTP requests to HTTPS and allow the use of client certificates.

In the Configure method, add the following code to enable SSL/TLS:

app.UseHttpsRedirection();

Configuration for Kestrel

To configure Kestrel to use a certificate in appsettings.json, you can add a Kestrel section to the file with the following properties:

{
"Kestrel": {
"EndPoints": {
"Https": {
"Url": "https://localhost:5001",
"Certificate": {
"Path": "mycert.crt",
"Password": "mycertpassword"
}
}
}
}
}

This will configure Kestrel to listen for HTTPS traffic on port 5001 and use the certificate stored in the mycert.crt file. The Password property is optional and should be specified if the certificate is protected by a password.

I hope you found this helpful, if you have any other questions, please let me know! Thanks

--

--

Alex Maher

.NET C# dev with 10+ yrs exp, self-taught & passionate web developer. Sharing tips & experiences in C# and web dev.