【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中呢?

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

但是,对于第二种“通过指纹在系统证书库中查找证书 ”的方式,在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】


相关文章
|
12天前
|
域名解析 网络协议 API
【Azure Container App】配置容器应用的缩放规则 Managed Identity 连接中国区 Azure Service Bus 问题
本文介绍了在 Azure Container Apps 中配置基于自定义 Azure Service Bus 的自动缩放规则时,因未指定云环境导致的域名解析错误问题。解决方案是在扩展规则中添加 `cloud=AzureChinaCloud` 参数,以适配中国区 Azure 环境。内容涵盖问题描述、原因分析、解决方法及配置示例,适用于使用 KEDA 实现事件驱动自动缩放的场景。
|
16天前
|
网络协议 API 网络安全
【Azure Function App】发现部分请求Function App遇见 403.72 报错(请求Body>100KB)
在调用Azure Function的HTTP Trigger时,发送POST请求偶尔出现403错误,且响应为空、Header信息少。经排查发现,当请求Body大于100KB时会触发403.72错误,原因是启用了“Client Certificate mode”为“Optional Interactive User”。解决方法是将该模式设置为“Ignore”。由于TLS重新协商机制限制,大请求体无法正常处理,导致此问题。
|
6天前
|
Java Shell Maven
【Azure Container App】构建Java应用镜像时候遇无法编译错误:ERROR [build 10/10] RUN ./mvnw.cmd dependency:go-offline -B -Dproduction package
在部署Java应用到Azure Container App时,构建镜像过程中出现错误:“./mvnw.cmd: No such file or directory”。尽管项目根目录包含mvnw和mvnw.cmd文件,但依然报错。问题出现在Dockerfile构建阶段执行`./mvnw dependency:go-offline`命令时,系统提示找不到可执行文件。经过排查,确认是mvnw文件内容异常所致。最终通过重新生成mvnw文件解决该问题,镜像成功构建。
|
Linux
5款优秀的Linux便携式应用
译文出自:5款优秀的Linux便携式应用
700 0
|
1月前
|
JSON 自然语言处理 Linux
linux命令—tree
tree是一款强大的Linux命令行工具,用于以树状结构递归展示目录和文件,直观呈现层级关系。支持多种功能,如过滤、排序、权限显示及格式化输出等。安装方法因系统而异常用场景包括:基础用法(显示当前或指定目录结构)、核心参数应用(如层级控制-L、隐藏文件显示-a、完整路径输出-f)以及进阶操作(如磁盘空间分析--du、结合grep过滤内容、生成JSON格式列表-J等)。此外,还可生成网站目录结构图并导出为HTML文件。注意事项:使用Tab键补全路径避免错误;超大目录建议限制遍历层数;脚本中推荐禁用统计信息以优化性能。更多详情可查阅手册mantree。
linux命令—tree
|
1月前
|
Unix Linux
linux命令—cd
`cd` 命令是 Linux/Unix 系统中用于切换工作目录的基础命令。支持相对路径与绝对路径,常用选项如 `-L` 和 `-P` 分别处理符号链接的逻辑与物理路径。实际操作中,可通过 `cd ..` 返回上级目录、`cd ~` 回到家目录,或利用 `cd -` 在最近两个目录间快速切换。结合 Tab 补全和 `pwd` 查看当前路径,能显著提升效率。此外,需注意特殊字符路径的正确引用及脚本中绝对路径的优先使用。
|
28天前
|
Linux
Linux命令拓展:为cp和mv添加进度显示
好了,就这样,让你的Linux复制体验充满乐趣吧!记住,每一个冷冰冰的命令背后,都有方法让它变得热情起来。
99 8
|
1月前
|
安全 Linux 定位技术
Linux环境下必备的基础命令概览
以上就是Linux系统中的基本命令和工具,掌握它们就能帮你在Linux世界里游刃有余。这其实就像是学习驾驭一辆新车,熟悉了仪表盘,调整好了座椅,之后的旅程就只需要享受风驰电掣的乐趣了。
48 4
|
2月前
|
Ubuntu 搜索推荐 Linux
详解Ubuntu的strings与grep命令:Linux开发的实用工具。
这就是Ubuntu中的strings和grep命令,透明且强大。我希望你喜欢这个神奇的世界,并能在你的Linux开发旅程上,通过它们找到你的方向。记住,你的电脑是你的舞台,在上面你可以做任何你想做的事,只要你敢于尝试。
166 32