Loading Azure certificate when NOT using custom do

2019-07-04 01:19发布

问题:

As I understand if someone doesn't want to use a custom domain name and instead plans on using *.azurewebsite.net domain assigned to the website by Azure, then HTTPS is already enabled with a certificate from Microsoft(I know this is not as secure as using a custom domain name). How would be I able to load this certificate programmatically. Currently I use the following method to load a certificate from local machine or Azure :

public static X509Certificate2 LoadFromStore(string certificateThumbprint,bool hostedOnAzure)
{
    var s = certificateThumbprint;

    var thumbprint = Regex.Replace(s, @"[^\da-zA-z]", string.Empty).ToUpper();

    var store = hostedOnAzure ? new X509Store(StoreName.My, StoreLocation.CurrentUser) : new X509Store(StoreName.Root, StoreLocation.LocalMachine); 

    try
    {
        store.Open(OpenFlags.ReadOnly);

        var certCollection = store.Certificates;

        var signingCert = certCollection.Find(X509FindType.FindByThumbprint, thumbprint, false);

        if (signingCert.Count == 0)
        {
            throw new FileNotFoundException(string.Format("Cert with thumbprint: '{0}' not found in certificate store. Also number of certificates in the sotre was {1}", thumbprint, store.Certificates.Count));
        }

        return signingCert[0];
    }
    finally
    {
        store.Close();
    }
}

I assume the culprit is the following line of code :

new X509Store(StoreName.My, StoreLocation.CurrentUser) 

because when I get an exception it tells me there is no certificate in the store although I pass the correct certificate Thumbprint(I grab the thumbprint from Chrome manually).

回答1:

You will not be able to access this certificate programmatically in your WebApp as this certificate is not really installed on the Azure WebApp. Azure WebApps have a front-end server which does a "kind of" SSL Offloading so the WebApp actually never has access to this particular certificate. Why exactly you want to read this certificate though ?

Typically if there is a need for certificates in WebApps, you would install client certificates and pass them to services for Authentication as mentioned in https://azure.microsoft.com/en-us/blog/using-certificates-in-azure-websites-applications/ and those certificates you can access programmatically (code snippet mentioned in the same article)

But I am not sure what exactly you want to achieve by reading the server certificate