Friday, March 15, 2024

Read TLS/SSL Certificate in Azure App Service from C# Code

Recently I was updating an old .NET Core web application to .NET 8 and the code was reading a certificate as follows.

private X509Certificate2 GetCertificateByThumbprint(string thumbprint)
{
    X509Store store = new (StoreName.My, StoreLocation.CurrentUser);
    store.Open(OpenFlags.ReadOnly);
    X509Certificate2Collection certificateCollection =  store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, true);
    return certificateCollection.OfType<X509Certificate2>().SingleOrDefault();
}

This piece of code wasn't working once the application is deployed to Azure App Service (Windows). The certificate is set up in App Service, but the code wasn't picking it up. As usual, QAs were insisting it used to work.

It seems I needed to add an app setting WEBSITE_LOAD_CERTIFICATES with the value of comma-separated certificate thumbprints in order for them be loaded and accessible from App Service code.

{
  "name""WEBSITE_LOAD_CERTIFICATES",
  "value""<comma-separated-certificate-thumbprints>",
  "slotSetting"false
}

You can read more on Use a TLS/SSL certificate in your code in Azure App Service. It contains instructions for other scenarios like loading a certificate from a file and loading a certificate in Linux/Windows containers.

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment