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

azure,app,service,net,tls,ssl,linux,container · 浏览次数 : 3

小编点评

在Linux环境中读取SSL证书(X509)文件,可以使用以下两种方法: **方法一:使用X509Store对象** ```csharp using Microsoft.Extensions.FileProviders; using System.Security.Cryptography.X509Certificates; public static string LoadPfx(string? filename, string password = \"\") { try { if (filename == null) filename = "contoso.com.pfx"; var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, certThumbprint, validOnly); if (certificates.Count == 0) return null; return certificates[0].ToString(); } catch (Exception ex) { return ex.Message; } } ``` **方法二:使用X509Certificate2对象** ```csharp using Microsoft.Extensions.FileProviders; using System.Security.Cryptography.X509Certificates; public static string LoadPfx(string? filename, string password = \"\") { try { if (filename == null) filename = "contoso.com.pfx"; var cert = new X509Certificate2(File.ReadAllBytes(filename), password); return cert.ToString(); } catch (Exception ex) { return ex.Message; } } ``` **注意:** * 在使用 `X509Store` 和 `X509Certificate2` 类读取证书时,需要指定证书的 thumbprint 或证书文件路径。 * 两种方法都假设证书文件是有效的 X509 证书,如果证书文件格式错误,读取结果可能失败。 * 两种方法都需要在运行代码之前加载证书文件到应用程序的磁盘存储中。

正文

在前一篇文章中,我们是把.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】

 

与【Azure App Service】.NET代码实验App Service应用中获取TLS/SSL 证书 (App Service Linux/Linux Container)相似的内容:

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

在前一篇文章中,我们是把.NET 8应用读取SSL证书(X509)示例部署在App Service Windows环境中,那么如果部署在Linux环境,以及Linux Container中呢? 根据前文中的第一种方法,直接在把证书文件包含在源文件中,通过相对路径读取证书文件的方式,经测试,可以正常工

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

在使用App Service服务部署业务应用,因为有些第三方的接口需要调用者携带TLS/SSL证书(X509 Certificate),在官方文档中介绍了两种方式在代码中使用证书: 1) 直接使用证书文件路径加载证书 new X509Certificate2 2) 从系统的证书库中通过指纹加载...

【Azure 应用服务】在App Service for Windows中实现反向代理

问题描述 如何在App Service for Windows(.NET Stack)中,如何实现反向代理呢? 正向代理:客户端想要访问一个服务器,但是它可能无法直接访问这台服务器,这时候这可找一台可以访问目标服务器的另外一台服务器,而这台服务器就被当做是代理人的角色 ,称之为代理服务器,于是客户端

【Azure 应用服务】Azure App Service(Windows)环境中如何让.NET应用调用SAP NetWeaver RFC函数

问题描述 在Azure App Service for Windows的环境中,部署.NET应用,其中使用了 SAP NetWeaver RFC函数 (需要加载 sapnwrfc.dll)。详细的错误为: “System.DllNotFoundException: Unable to load DL

【Azure App Service】通过Visual Studio部署Azure App Service 遇见 401 'Unauthorized'错误

Error : Web deployment task failed. (Connected to the remote computer ("javatest02.scm.chinacloudsites.cn") using the Web Management Service, but could not authorize. Make sure that you are using the

【Azure App Service for Windows】 PHP应用出现500 : The page cannot be displayed because an internal server error has occurred. 错误

[500 The page cannot be displayed because an internal server error has occurred.] [scriptProcessor could not be found in "fastCGI" application configuration] [EXECUTE|500|0|0x585|CONFIG_SUCCESS|PHP7

【Azure App Service】Local Git App Service的仓库代码遇见卡住不Clone代码的问题

问题描述 启用App Service Local Git 部署,在Clone 代码库到本地时候,卡在Clone ‘xxxxxx’ ... ... 一动不动的问题? 问题解答 因为Git Clone没有任何日志输出,所以在其他IDE上也尝试Git App Service的代码库。在intellj的gi

【Azure App Service】Web Job 报错 UNC paths are not supported. Defaulting to Windows directory.

问题描述 PHP的Web Job,通过artisan来配置路径启动PHP任务,相关启动脚本如下: artisan_path = "d:\\home\\site\\wwwroot"; cd ${artisan_path} echo "\n" pwd php artisan schedule:run 但

【Azure App Service】为部署在App Service上的PHP应用开启JIT编译器

问题描述 在App Service for linux上创建一个PHP应用,通过 phpinfo() 查看PHP的扩展设置,发现JIT没有被开启, jit_buffer_size 大小为0. 那么,在App Service的环境中,如何开启JIT呢? 问题解答 PHP 8在PHP的内核中添加了JIT

【Azure App Service for Linux】NodeJS镜像应用启动失败,遇见 RangeError: Incorrect locale information provided

问题描述 在App Service For Linux 中,部署NodeJS应用,应用启动失败。 报错信息为: 2023-08-29T11:21:36.329731566Z RangeError: Incorrect locale information provided2023-08-29T11: