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



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

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

我能找到的最接近的在下面和这里的文档中。

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

但是,这显然是上传新证书,而不是使用现有证书。ForHostName()调用后还有另外两个选项:

WithExistingAppServiceCertificateOrder(certificateOrder)

WithNewStandardSslCertificateOrder(certificateOrderName)

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

我在 REST API 文档中也看不到任何内容。

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

显然,

这并不重要,因为我在 9 个月后才找到答案。

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

await azure
        .WebApps
        .Inner
        .CreateOrUpdateHostNameBindingWithHttpMessagesAsync(
            resourceGroupName, 
            webAppName, 
            domain,
            new HostNameBindingInner(
                azureResourceType: AzureResourceType.Website,
                hostNameType: HostNameType.Verified,
                customHostNameDnsRecordType: CustomHostNameDnsRecordType.CName,
                sslState: SslState.SniEnabled,
                thumbprint: thumbprint));
<</div> div class="one_answers">

据我所知,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());
            }

此解决方案适用于 2021 年。只需知道证书的指纹,它应与 Web 应用位于同一资源组中。

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

最新更新