Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET X509Certificate2 access denied when hosted in IIS

I am having the below piece of ASP.NET code to load a pfx file from a folder

var certificatePath = $"{HttpContext.Current.Server.MapPath("~")}{certFolderName}\\{certFileName}";
return new X509Certificate2(certificatePath, certPassword, X509KeyStorageFlags.MachineKeySet);

This code works fine in local IIS. However the same code when moved to our QA servers its throws Access Denied error as below.

enter image description here

I had gone through many forums and got to know that this is mostly a permission issue in accessing the folder C:\ProgramData\Microsoft\Crypto\RSA\MachineKey. I have verified the access for this folder in our server and its all fine. The 'Everyone' user has read & write access. So ideally there shouldn't be any access denied error. I even gave explicit Full Control access to the identity of App Pool, but still doesn't work. I am trying to understand what else could cause this access denied problem.

like image 201
Ashok Avatar asked Jan 29 '26 08:01

Ashok


1 Answers

return new X509Certificate2(certificatePath, certPassword, X509KeyStorageFlags.MachineKeySet);

the problem is with last parameter. Your application (app pool identity) doesn't have permissions to access local machine store. You should either use Current User store (for persistent key storage) or ephemeral if the key must be accessed only in runtime.

like image 136
Crypt32 Avatar answered Feb 01 '26 07:02

Crypt32



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!