【Azure App Service】.NET代码实验App Service应用中获取TLS/SSL 证书 (App Service Linux/Linux Container)

在前一篇文章中,我们是把.NET 8应用读取SSL证书(X509)示例部署在App Service Windows环境中,那么如果部署在Linux环境,以及Linux Container中呢?

根据前文中的第一种方法,直接在把证书文件包含在源文件中,通过相对路径读取证书文件的方式,经测试,可以正常工作。

但是,对于第二种“通过指纹在系统证书库中查找证书 ”的方式,在Linux系统中,是不能使用 X509Store(StoreName.My, StoreLocation.CurrentUser) 中查找的方式。

经过测试验证,在App Service Linux( 包含Linux Container)证书页面上传的证书后,系统会把证书保存为文件。存储在 /var/ssl/ 文件夹中,可以通过ssh 方式查看:

  1. 进入App Service Kudu(高级工具)页面: https://<yourwebappname>.scm.chinacloudsites.cn/webssh/host 
  2. 点击SSH目录,输入cd 目录命令: cd /var/ssl/private 后,列举全部文件: ls -ll

 

在.NET 8代码中的正确读取私有证书 (.pfx)的代码示例:

    public static string FindPfxbyThubmprintinLinux(string thumbprint)
    {
        if (string.IsNullOrEmpty(thumbprint))
            return $"Certificate with thumbprint {thumbprint} was not found";

        string finalPath = $"/var/ssl/private/{thumbprint}.p12";
        var bytes2 = File.ReadAllBytes(finalPath);
        var cert = new X509Certificate2(bytes2);
        return cert.ToString(); 
    }

注意:

  • WEBSITE_LOAD_CERTIFICATES  配置不可少
  • 门户上的证书添加后,需要重启站点,等待实例中出现证书文件。(通常在15分钟左右后才能在目录中看见 thumbprint.p12文件)

 

附录:示例代码(.NET 8.0 顶级语句 program.cs)

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.FileProviders;
using System.Security.Cryptography.X509Certificates;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseHttpsRedirection();

app.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "Images")),
    RequestPath = new PathString("/Images")
});



app.MapGet("/loadpfxbyname", ([FromQuery(Name = "name")] string filename, [FromQuery(Name = "pwd")] string pwd) =>
{
    var content = pfxTesting.LoadPfx(filename, pwd);
    return content;
});

app.MapGet("/loadpfx/{pwd}", (string pwd) =>
{

    var content = pfxTesting.LoadPfx(null, pwd);
    return content;
});

app.MapGet("/findpfx/{certThumbprint}", (string certThumbprint) =>
{

    var content = pfxTesting.FindPfx(certThumbprint);
    return content;
});



app.Run();

class pfxTesting
{
    public static string LoadPfx(string? filename, string password = "")
    {
        try
        {
            if (filename == null) filename = "contoso.com.pfx";

            var bytes = File.ReadAllBytes(filename);
            var cert = new X509Certificate2(bytes, password);

            return cert.ToString();
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

    public static string FindPfx(string certThumbprint = "")
    {
        try
        {
            bool validOnly = false;
            using (X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))
            {
                certStore.Open(OpenFlags.ReadOnly);

                X509Certificate2Collection certCollection = certStore.Certificates.Find(
                                            X509FindType.FindByThumbprint,
                                            // Replace below with your certificate's thumbprint
                                            certThumbprint,
                                            validOnly);
                // Get the first cert with the thumbprint
                X509Certificate2 cert = certCollection.OfType<X509Certificate2>().FirstOrDefault();

                if (cert is null)
                    return FindPfxbyThubmprintinLinux(certThumbprint);
                    //throw new Exception($"Certificate with thumbprint {certThumbprint} was not found");

                return cert.ToString();

            }
        }
        catch (Exception ex) { return ex.Message; }
    }

    public static string FindPfxbyThubmprintinLinux(string thumbprint)
    {
        if (string.IsNullOrEmpty(thumbprint))
            return $"Certificate with thumbprint {thumbprint} was not found";

        string finalPath = $"/var/ssl/private/{thumbprint}.p12";
        var bytes2 = File.ReadAllBytes(finalPath);
        var cert = new X509Certificate2(bytes2);
        return cert.ToString(); 
    }
}

 

 

参考资料

在 Linux/Windows 容器中加载证书 : https://docs.azure.cn/zh-cn/app-service/configure-ssl-certificate-in-code#load-certificate-in-linuxwindows-containers

GetX509CertificateLinux(string thumbprint)  :

https://learn.microsoft.com/en-us/answers/questions/1055731/application-error-on-linux-running-net-core

Load Certificate on Linux Web App #19305 : https://github.com/MicrosoftDocs/azure-docs/issues/19305

 

【END】

 

posted @ 2024-06-01 09:25  路边两盏灯  阅读(126)  评论(0编辑  收藏  举报