如何以编程方式将现有SSL证书应用于Azure Web应用程序

时间:2017-03-24 17:40:57

标签: c# azure azure-web-sites

我正在使用Azure Fluent Management API来自动化我们的部署过程。到目前为止,我遇到的问题很少。

我们已将SSL证书上传到Azure,并可通过Azure门户手动将其绑定到网站。但我找不到以编程方式执行此操作的机制。

我能找到的最接近的文件位于文档here下方。

webApp.Update()
    .DefineSslBinding()
    .ForHostname(domainName)
    .WithPfxCertificateToUpload(pfxFile, password)
    .WithSniBasedSsl()
    .Attach();

然而,这显然是在上传新证书,而不是使用现有证书。 ForHostName()致电后还有其他两个选项:

WithExistingAppServiceCertificateOrder(certificateOrder)

WithNewStandardSslCertificateOrder(certificateOrderName)

但我的理解是这些与通过Azure / Microsoft购买证书有关。

我也无法在REST API documentation中看到任何内容。

那么,如何在代码中将现有证书与Web应用相关联?

3 个答案:

答案 0 :(得分:1)

显然这并不重要,因为我在9个月后才发现answer

无论如何,以下答案将从提供的链接中复制。

await azure
        .WebApps
        .Inner
        .CreateOrUpdateHostNameBindingWithHttpMessagesAsync(
            resourceGroupName, 
            webAppName, 
            domain,
            new HostNameBindingInner(
                azureResourceType: AzureResourceType.Website,
                hostNameType: HostNameType.Verified,
                customHostNameDnsRecordType: CustomHostNameDnsRecordType.CName,
                sslState: SslState.SniEnabled,
                thumbprint: thumbprint));

答案 1 :(得分:0)

据我所知,Azure Fluent Management API的版本是1.0.0-beta50,因此它可能不包含将现有证书添加到主机名的方法。

我建议你可以使用REST API来实现它。

我建议您发送请求到以下网址。

Url: https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Web/sites/{snapshotName}?api-version={api-version}

Method: PUT

Parameter:
subscriptionId  The identifier of your subscription where the snapshot is being created.
resourceGroup   The name of the resource group that will contain the snapshot.
WebappName    The name of the WebappName. 
api-version The version of the API to use.

Request content:
{
  "properties": {
    "HostNameSslStates": [ 
      {
        "SslState": "the SSL state",
        "ToUpdate": "True",
       "Thumbprint": "The Thumbprint of the certificate, you could find it in the portal",
        "Name": "yourwebsitename"
      }
    ]
},
  "kind": "app",
  "location": "yourlocation",
  "tags": {
    "hidden-related:/subscriptions/{subscriptionId}/resourcegroups/{resourceGroup}/providers/Microsoft.Web/serverfarms/{yourserviceplan}": "empty"
  }
}

更多细节,您可以参考下面的C#代码:

Json.txt:

{
  "properties": {
    "HostNameSslStates": [ 
      {
        "SslState": "1",
        "ToUpdate": "True",
        "Thumbprint": "BE58B05C5CADE03628D0D58B369D0DA6F535B0FA",
        "Name": "test.azureclubs.com"
      }
    ]
},
  "kind": "app",
  "location": "East Asia",
  "tags": {
    "hidden-related:/subscriptions/xxxxxxxxxxxxxxxx/resourcegroups/xxxxxxxxxxxxx/providers/Microsoft.Web/serverfarms/BrandoTestServicePlan": "empty"
  }
}

代码:

string body = File.ReadAllText(@"D:\json.txt");

            // Display the file contents to the console. Variable text is a string.

            string tenantId = "xxxxxxxxxxxxxxxxxxxxxxxxx";
            string clientId = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
            string clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxx";
            string subscriptionid = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
            string resourcegroup = "BrandoSecondTest";

            string appname = "BrandoTestApp";
            string version = "2015-08-01";

            string authContextURL = "https://login.windows.net/" + tenantId;
            var authenticationContext = new AuthenticationContext(authContextURL);
            var credential = new ClientCredential(clientId, clientSecret);
            var result = authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/", clientCredential: credential).Result;

            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }

            string token = result.AccessToken;

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Web/sites/{2}?api-version={3}", subscriptionid, resourcegroup, appname, version));

            request.Method = "PUT";
            request.Headers["Authorization"] = "Bearer " + token;


            request.ContentType = "application/json";
            try
            {
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(body);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            // Get the response
            var httpResponse = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                Console.WriteLine(streamReader.ReadToEnd());
            }

答案 2 :(得分:0)

此解决方案适用于 2021 年。您只需要知道证书的指纹,并且它应该与您的网络应用在同一资源组中。

var webApp = azure.WebApps
            .GetById("webapp resource Id goes here")
            .Update()
            .DefineSslBinding()
            .ForHostname("host name goes here")
            .WithExistingCertificate("thumbprint goes here")
            .WithSniBasedSsl()
            .Attach()
            .Apply();