使用密钥库中的证书创建Azure Web应用SSL绑定

时间:2019-04-16 20:58:26

标签: c# azure azure-web-sites

我正在尝试使用从密钥库检索的证书将SSL添加到Azure Web应用程序。我没有找到通过门户网站执行此操作的方法,因此我一直在尝试使用Azure API进行操作。

我可以使用以下代码来获取证书的机密并将其转换为X509证书:

 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);

老实说,我不知道下一步该怎么做。我一直在研究Microsoft.Azure.Management.Fluent库,但无法正常工作。

我朝着正确的方向前进吗?有没有可能有帮助的例子?

1 个答案:

答案 0 :(得分:1)

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.