2

I am facing an issue while trying to load a p12 certificate file in a C# MVC web application when login is through an AD account.

The error we get when loading the certificate is: The computer must be trusted for delegation and the current user account must be configured to allow delegation.

The code for loading the certificate:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

var handler = new WebRequestHandler();

var certificate = new X509Certificate2Collection();
certificate.Import(@"D:\certificate.p12", "password", X509KeyStorageFlags.DefaultKeySet);
handler.ClientCertificates.AddRange(certificate);
handler.ServerCertificateValidationCallback = ValidateServerCertificate;

var client = new HttpClient(handler)
{
    BaseAddress = new Uri(chargeCodeServer)
};

We get an exception at the following line:

certificate.Import(@"D:\certificate.p12", "password", X509KeyStorageFlags.DefaultKeySet);

The stack trace:

The requested operation cannot be completed. The computer must be trusted for delegation and the current user account must be configured to allow delegation.
at System.Security.Cryptography.X509Certificates.X509Certificate2Collection.LoadStoreFromFile(String fileName, String password, UInt32 dwFlags, Boolean persistKeyContainers)
at System.Security.Cryptography.X509Certificates.X509Certificate2Collection.Import(String fileName, String password, X509KeyStorageFlags keyStorageFlags)

The same code runs fine in a console application.

The certificate is being loaded for calling a web API over https.

Please let me know if any more information is needed.

Nisha
  • 38
  • 3
  • Try UserKeySet instead of DefaultKeySet. One of the private keys might have a "machine store" marker and your AppPoolIdentity user won't have permission for that. – bartonjs Sep 05 '17 at 16:06

2 Answers2

2

I had the same error and for me worked this:

certificate = new X509Certificate2(keyCertificateFilePath, keyCertificatePassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
Daniel0b1b
  • 2,271
  • 2
  • 11
  • 9
0

If someone else is still facing this issue, giving access to the certificate for the account running the web application worked for me.

Unlike a console application,to enable an ASP.NET Web application to use a client certificate, you must install the client certificate in the local machine store. When you install a client certificate in the local machine store, the client certificate is only available for user accounts in the Administrators group and for the user who installed the client certificate. Therefore, you must grant access to the client certificate for the user account that is used to run the ASP.NET Web application.

Nisha
  • 38
  • 3