Search code examples
c#.netx509certificate2

Identityserver fails to load selfsigned certificate


I'm trying to set a Certificate for identityserver and it keeps failing with a "no access to private key error". Taking it out of identityserver, the following code throws an access denied error

static X509Certificate2 GetCertificateFromDisk()
{
    using (var stream = File.Open(@"patht-to-pfx", FileMode.Open))
    {
        var cert = new X509Certificate2(ReadStream(stream), "password", X509KeyStorageFlags.MachineKeySet);
        return cert;
    }
}

When running the code as administrator it works fine, not when running it under my own account. Eventually I want to run it as localsystem.

I even added 'Everyone' under the certificates private key permissions in my local computer certificate store, screenprint here ... still I get the exception.

What is wrong here? Going Crazy about it

Update

Great tips from CryptoGuy in the answer below. Important note: Opening the file is not correct only Identityserver3 still failed when getting the certificate from the store. What made it work was to regenerate the certificate using Keith Sparkjoy's tool SerfCert. My previous certificate was generated using powershell. So keep in mind that powershell certificates have issues with accessibility of private key. Thanks to Keith for the tool!


Solution

  • There are few things to consider.

    1) you are performing write access to Local Machine store. X509KeyStorageFlags.MachineKeySet attempts to save private key to Local Machine store. Therefore, you need administrator permissions to write there. You should remove this flag to perform read-only access

    2)

    Documentation says that adding permissions in MMC (manage private key-option on a certificate) should allow this, but it doesn't seem to work

    it works on an already saved private keys.

    What you really should do is to import certificate and private key to Local Machine store and then configure your application to reference installed certificate.

    3) if your application runs under unpriveleged account and the key don't need to be shared, then you should use Current User store.