Search code examples
c#.netazurex509azure-cloud-services

Get x509 Certificate In Azure Cloud Service


I need to use a certificate for authentication with an Azure Key Vault, but I cannot access the key I have uploaded. I have taken these steps:

Uploaded key (.pfx) to Cloud Service via the portal.

Added this to ServiceConfiguration

<Certificates>
    <Certificate name="keyvault" thumbprint="<my_thumbprint>" thumbprintAlgorithm="sha1" />
</Certificates>

Added this to ServiceDefinition

<Certificates>
  <Certificate name="keyvault" storeLocation="LocalMachine" storeName="CA" />
</Certificates>    

Using this code to retrieve key:

var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
StoreLocation.LocalMachine);
try
{
    store.Open(OpenFlags.ReadOnly);
    var col = store.Certificates.Find(X509FindType.FindByThumbprint,
                <thumbprint_value>, false); // Don't validate certs, since the test root isn't installed.
    if (col == null || col.Count == 0)
                return null;
            return col[0];
}
finally
{
    store.Close();
}

However, when I start the service I see this exception:

Value cannot be null.
Parameter name: certificate

Is there any additional configuration I need?


Solution

  • The reason you're getting this error is because you're asking Fabric Controller to install the certificate in one location

    <Certificate name="keyvault" storeLocation="LocalMachine" storeName="CA" />
    

    while your code is reading the certificate from other location.

    var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
    

    Please make sure that you use same location in both places.

    I would make the following change in csdef file:

    <Certificate name="keyvault" storeLocation="LocalMachine" storeName="My" />
    

    And the following in the code:

    var store = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine);