I'm done configuring IdentityServer.v3 with IdentityManager and everything is working pretty much how I want. The only thing left is changing the X.509 certificate to a custom self-signed one. I am using the code here to load my embedded certificate. What I'm doing is copying my .pfx file to the config folder and changing the certificate name and password for that pfx in the Cert.cs file. Also, I am setting "Build Action: Embedded Resource" and "Copy to Output Directory: Do not copy" in the new pfx file properties.
When I publish my solution, I getting an application wide error like this.
The system cannot find the file specified.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Security.Cryptography.CryptographicException: The system cannot find the file specified.
Is there a specific way of creating the pfx file? I created mine using makecert.exe
and pvk2pfx.exe
files. Also, I am using this certifice for securing the domain on which IDSRV3 is being hosted. Without touching any of certificate configuration, both IdentityServer.v3 and IdentityManager work without errors.
What am I missing here?
First, the answer to my question. After making some(!) search, I found out that in order to load embedded certificates when hosting in IIS, we should make a little change in the Application Pool configuration. In the Advanced Settings of the Application Pool, change the value of the "Load User Profile" to true. It appears to be certificates are loaded in the user profile and we some how need to let IIS to access that info by this config change.
As for loading certificated from the Windows Certificate Store, here is the code I used.
public static X509Certificate2 GetCert()
{
X509Certificate2 cert = FindCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySerialNumber, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); // serial number is a 32 digit GUID without any white spaces or dashes. It can be found from details of cert file
return cert;
}
static X509Certificate2 FindCertificate(StoreLocation location, StoreName name, X509FindType findType, string findValue)
{
X509Store store = new X509Store(name, location);
try {
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection col = store.Certificates.Find(findType, findValue, false);
return col[0]; }
finally
{
store.Close();
}
}
Make sure that you loaded the certificate in Windows Certificate Store in the Personal folder and used the .pfx file.
I hope that helps others who are stuggling with certificates as I did.
EDIT: It's important that, if you find the certificate by serial number, you should write the serial number with UPPER CASE letters. When you copy the serial number from MMC console, it's lower cased and VS loads the certificates to the store with UPPER CASE letters.