I have a Azure Function app on a shared app service plan and I don't want to import my certificates through the Azure portal. That is because this app service plan is shared within the organisation and these certificates are client certificates that I want to be sure of that I am the only one able to access them.
So I import them using Function app settings (and I am moving them to the Vault for even more security).
byte[] bytearray; // PFX file, imported from settings using base64 encoding
string password; // Imported from settings
certificates = new X509Certificate2Collection();
certificates.Import(bytearray, password, X509KeyStorageFlags.UserKeySet | X509KeyStorageFlags.PersistKeySet);
Using them goes like this
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
foreach (var cert in certificates)
handler.ClientCertificates.Add(cert);
But the connection is refusing with the error 'The credentials supplied to the package were not recognized'.
I tried a few things
If you are setting up X509Certificate2
instance from a pfx file or cert encoded containing private key, you may run into CryptographicException: The system cannot find the file specified..
The reason is Windows stores private key as a file under a user profile directory. By default, Azure Web App (AppService) does not load user profile (avoid overhead for majority scenarios where it is not needed). Hence, the The system cannot find the file specified. issue. To work around, set the below appSetting to enable User Profile.
WEBSITE_LOAD_USER_PROFILE=1
By setting the App Setting WEBSITE_LOAD_USER_PROFILE = 1
, Azure Websites will load user profiles for the given application, and thus applications can load certificates from PFX files.
References:
https://azure.microsoft.com/en-in/blog/pdf-generation-and-loading-file-based-certificates-in-azure-websites/
https://github.com/projectkudu/kudu/wiki/Configurable-settings#the-system-cannot-find-the-file-specified-issue-with-x509certificate2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With