Search code examples
c#azureazure-keyvaultx509certificate2sustainsys-saml2

Accessing Certificate Programatically for SAML2


Setup:

I have a .Net Framework WebForms app and just setup SAML2 using Sustainsys.Saml2 setup on Azure. I'm also using Git for version control (VC) and Azure Key Vault for App Settings and Connection Strings.

Question:

What are other ways I can store and access the certificate for SAML2, even if I can access it programmatically (I'm currently accessing/setting the certificate programmatically)?

I want to prevent adding certificates to our VC as well as adding it manually to the Azure directory.

I tried looking into Key Vault Certificates, but I'm unsure if I can even use this.


Solution

  • You can upload your certificate to your Azure App Service --> TSLSSL setting --> Private Key Certificates (.pfx).

    Once uploaded there you can retrieve it programmatically via C# with the following:

    public static X509Certificate2 GetX509Certificate2(string certThumbprint, bool validOnly = true, StoreName storeName = StoreName.My, StoreLocation storeLocation = StoreLocation.CurrentUser) {
        using (var certStore = new X509Store(storeName, storeLocation)) {
            var certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, certThumbprint, validOnly);
            // Get the first cert with the thumbprint
            var cert = (X509Certificate2) certCollection.OfType<X509Certificate>().FirstOrDefault();
            certStore.Close();
            return cert;
        }
    }
    

    Call it via:

    var cert = GetX509Certificate2(certificateThumbprint, false, storeLocation: StoreLocation.LocalMachine);
    

    Personally, so it can work locally, deployed and on any of our devs computers, I use the following code so that it can search different locations where it may be stored:

    var cert = GetX509Certificate2(certificateThumbprint, false, storeLocation: StoreLocation.CurrentUser);
    
    if (cert == null) {
        cert = GetX509Certificate2(certificateThumbprint, false, storeLocation: StoreLocation.LocalMachine);
    }