Search code examples
azureasp.net-core.net-corex509certificate2cryptographicexception

CryptographicException: System cannot find the specified file in azure app service


I have a .net core app with openiddict configured and published on azure app service but while loading the application following exception occurs:

---> System.Security.Cryptography.CryptographicException: The system cannot find the file specified.
   at System.Security.Cryptography.X509Certificates.CertificatePal.FilterPFXStore(ReadOnlySpan`1 rawData, SafePasswordHandle password, PfxCertStoreFlags pfxCertStoreFlags)
   at System.Security.Cryptography.X509Certificates.CertificatePal.FromBlobOrFile(ReadOnlySpan`1 rawData, String fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
   at System.Security.Cryptography.X509Certificates.X509Certificate..ctor(Byte[] rawData, String password, X509KeyStorageFlags keyStorageFlags)
   at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(Byte[] rawData, String password, X509KeyStorageFlags keyStorageFlags)
   at Azure.Security.KeyVault.Certificates.CertificateClient.DownloadCertificate(DownloadCertificateOptions options, CancellationToken cancellationToken)
   at Azure.Security.KeyVault.Certificates.CertificateClient.DownloadCertificate(String certificateName, String version, CancellationToken cancellationToken)

It works fine in my local system. I have verified the downloaded certificates from keyvault while debugging.

Following is my code to download the certificate from the Azure.KeyVault:

       services.AddOpenIddict()
            .AddServer(options =>
            {
                var vaultUri = // Uri of Azure keyvault
                var client = new CertificateClient(vaultUri, new DefaultAzureCredential());
                var encryptionCertificate = client.DownloadCertificate("<encryption certificate name>").Value;
                var signingCertificate = client.DownloadCertificate("<signing certificate name>").Value;

                options.AddEncryptionCertificate(encryptionCertificate );
                options.AddSigningCertificate(signingCertificate );
            });

Solution

  • After spending quite some time on this problem I fixed it by putting WEBSITE_LOAD_USER_PROFILE=1 config value in the app settings of my azure app service to access the certificate store.

    Another equivalent setting which will enable User Profile indirectly is WEBSITE_LOAD_CERTIFICATES = *

    Details of these are here and here