Brian Selle
Brian Selle

Reputation: 131

Create Azure web app SSL binding using certificate from key vault

I'm trying to add SSL to an Azure web app using a certificate retrieved from the key vault. I don't see a way to do this via the portal so I've have been trying to do it with the Azure API.

I'm able to get the certificate secret and convert it to a X509 certificate using the following code:

 AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
 KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

 SecretBundle secret2 = await keyVaultClient.GetSecretAsync(KEY_VAULT_IDENTIFIER);
 string pass = null;
 X509Certificate2 certificate = new X509Certificate2(Convert.FromBase64String(secret2.Value), pass, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

I honestly don't know what to do next. I've been looking into the Microsoft.Azure.Management.Fluent library but haven't been able to get anything working.

Am I headed in the right direction? Are there any examples out there that may help?

Upvotes: 1

Views: 414

Answers (1)

Rohit Saigal
Rohit Saigal

Reputation: 9664

For C# code, you can make use of Azure Management Libraries for .NET

You can use following 2 Nuget packages:

  • Microsoft.Azure.Management.Fluent

  • Microsoft.Azure.Management.ResourceManager.Fluent

Authentication

You can read the guidance here

First step will be to create a Service Principal for RBAC, give it permissions on the relevant resource group and then use the clientId, secret and tenant information in code ahead.

az ad sp create-for-rbac

Code

        string clientId = "xxxxx-xxx-xxxx";
        string clientSecret = "xxxxx-xxx-xxxx";
        string tenant = "xxxxx-xxx-xxxx";
        string subscriptionId = "xxxxx-xxx-xxxx";

        var creds = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenant, AzureEnvironment.AzureGlobalCloud);
        var azure = Azure.Authenticate(creds).WithSubscription(subscriptionId);

        var app1 = azure.WebApps.GetByResourceGroup("rgAppService", "MyAPIServiceName");

        app1.Update()
            .DefineSslBinding()
            .ForHostname("MyHostName")
            .WithExistingCertificate("<Thumbprint of the certificate>")
            .WithSniBasedSsl()  // could use different method .WithIpBasedSsl in case that is relevant
            .Attach()
            .Apply();

Detailed Code Sample on GitHub

Managing Web Apps with custom domains in C#

This sample does a lot of things like creating the Apps, domains etc., so pick the parts that are applicable for you.

Upvotes: 2

Related Questions