检查和更新 Azure Web 应用服务上自定义域的 SSL 证书

问题描述 投票:0回答:1

我目前正在寻找编写一个 C# 函数来查询我的 Azure Web 应用服务并检查自定义域是否有效。

在此过程中,我使用更新的 Azure.ResourceManager 库来查询 ARM API。到目前为止我已经。

internal async Task<List<AppServiceCustomDomainResult>> CreateOrUpdateCustomDomains(string? appServiceName, List<AppServiceCustomDomains> activeDomains)
{
    var result = new List<AppServiceCustomDomainResult>();

    _log.LogInformation("Connecting to Azure");

    var azure = GetAzureSubscription();
    await foreach (var site in azure.GetWebSitesAsync())
    {
        if (site.HasData && site.Data.Name == appServiceName)
        {
            var hostNameBindings = site.GetSiteHostNameBindings();

            foreach (var binding in hostNameBindings)
            {
                if (activeDomains.Any(c => c.SniName != null && c.SniName.EndsWith(checkName)))
                {
                    // Check SSL
                    if (binding.Data.SslState == HostNameBindingSslState.SniEnabled)
                    {
                        
                    }
                }
                else
                {
                    // Add SSL

                    // Add Binding
                }
            }

            break;
        }
    }

    return result;
}

接下来我要寻找的是一种检查绑定上的 SSL 证书的方法,以查看它是否已过期并需要更新/删除。我还需要添加一个,但我还没有达到那个阶段。无论如何,我似乎找不到让 SSL 检查其过期的方法,但是有人能找到吗?我引用的是https://learn.microsoft.com/en-us/rest/api/appservice/web-apps/get-host-name-binding,但是示例很少。

我也尝试过

site.GetSitePublicCertificates()
,但我认为这与其他事情有关,因为没有返回任何内容,尽管我认为我目前只在测试中管理了证书..

c# azure-web-app-service azure-resource-manager
1个回答
0
投票

您可以利用 Rest API 列出所有自定义域,并使用与创建和更新具有主机绑定的自定义域相关的另一个 API,并在 C# 代码中使用 GET、PUT 或 POST 请求调用它,如下所示:-

我的C# Http Trigger函数代码:-

Rest API 参考:-

参考:-我的SO线程答案

using Azure.Core;
using Azure.Identity;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System.Net.Http.Json;

namespace FunctionApp1
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            var token = await GetAccessToken("83331f4e-7f45-4ce4-99ed-af9038592395", "c0c952e9-5254-45b5-b838-6d26a31435cb", "Cnd8Q~Ro6wHqvMGQUyvqrEgguL0nl-gYmTYkDcPI");
            var results = await GetResults(token);

            return new OkObjectResult(results);
        }

        private static async Task<string> GetAccessToken(string tenantId, string clientId, string clientKey)
        {
            var credentials = new ClientSecretCredential(tenantId, clientId, clientKey);
            var result = await credentials.GetTokenAsync(new TokenRequestContext(new[] { "https://management.azure.com/.default"
}), default);
            return result.Token;
        }

        private static async Task<string> GetResults(string token)
        {
            var httpClient = new HttpClient
            {
                BaseAddress = new Uri("https://management.azure.com/subscriptions/")
            };

            string URI = $"0151c365-f598-44d6-b4fd-e2b6e97cb2a7/providers/Microsoft.DomainRegistration/domains?api-version=2022-03-01";

            httpClient.DefaultRequestHeaders.Remove("Authorization");
            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            HttpResponseMessage response = await httpClient.GetAsync(URI);

            var HttpsResponse = await response.Content.ReadAsStringAsync();
            //var JSONObject = JsonConvert.DeserializeObject<object>(HttpsResponse);

            //return response.StatusCode.ToString();
            return HttpsResponse;
        }
    }
}

输出:-

enter image description here

enter image description here

类似,您可以使用此 API Web 应用程序 - 创建或更新主机名绑定 - REST API(Azure 应用程序服务)|微软学习

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace FunctionApp1
{
    public static class Function1
    {
        [FunctionName("UpdateHostNameBindingFunction")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            var requestParams = JsonConvert.DeserializeObject<HostNameBindingRequest>(requestBody);

            var token = await GetAccessToken("<tenant-id>", "<client-id>", "<client-secret>");
            var response = await UpdateHostNameBinding(token, requestParams);

            return new OkObjectResult(response);
        }

        private static async Task<string> GetAccessToken(string tenantId, string clientId, string clientSecret)
        {
            var credentials = new ClientSecretCredential(tenantId, clientId, clientSecret);
            var result = await credentials.GetTokenAsync(new TokenRequestContext(new[] { "https://management.azure.com/.default" }), default);
            return result.Token;
        }

        private static async Task<string> UpdateHostNameBinding(string token, HostNameBindingRequest requestParams)
        {
            var httpClient = new HttpClient();
            string endpoint = $"https://management.azure.com/subscriptions/{requestParams.SubscriptionId}/resourceGroups/{requestParams.ResourceGroupName}/providers/Microsoft.Web/sites/{requestParams.AppName}/slots/{requestParams.Slot}/hostNameBindings/{requestParams.HostName}?api-version=2022-03-01";

            var requestBody = new
            {
                kind = requestParams.Kind,
                properties = new
                {
                    azureResourceName = requestParams.AzureResourceName,
                    azureResourceType = requestParams.AzureResourceType,
                    customHostNameDnsRecordType = requestParams.CustomHostNameDnsRecordType,
                    domainId = requestParams.DomainId,
                    hostNameType = requestParams.HostNameType,
                    siteName = requestParams.SiteName,
                    sslState = requestParams.SslState,
                    thumbprint = requestParams.Thumbprint
                }
            };

            var content = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            HttpResponseMessage response = await httpClient.PutAsync(endpoint, content);

            if (response.IsSuccessStatusCode)
            {
                string responseContent = await response.Content.ReadAsStringAsync();
                return responseContent;
            }
            else
            {
                return $"Error: {response.StatusCode}";
            }
        }
    }

    public class HostNameBindingRequest
    {
        public string Kind { get; set; }
        public string AzureResourceName { get; set; }
        public string AzureResourceType { get; set; }
        public string CustomHostNameDnsRecordType { get; set; }
        public string DomainId { get; set; }
        public string HostNameType { get; set; }
        public string SiteName { get; set; }
        public string SslState { get; set; }
        public string Thumbprint { get; set; }
        public string SubscriptionId { get; set; }
        public string ResourceGroupName { get; set; }
        public string AppName { get; set; }
        public string Slot { get; set; }
        public string HostName { get; set; }
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.