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

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

在使用App Service服务部署业务应用,因为有些第三方的接口需要调用者携带TLS/SSL证书(X509 Certificate),在官方文档中介绍了两种方式在代码中使用证书:

1) 直接使用证书文件路径加载证书

2) 从系统的证书库中通过指纹加载证书

本文中,将分别通过代码来验证以上两种方式.

 

第一步:使用PowerShell创建自签名证书

参考文档 : 生成自签名证书概述  https://learn.microsoft.com/zh-cn/dotnet/core/additional-tools/self-signed-certificates-guide#with-powershell

$cert = New-SelfSignedCertificate -DnsName @("mytest.com", "www.mytest.com") -CertStoreLocation "cert:\LocalMachine\My"
$certKeyPath = 'C:\MyWorkPlace\Tools\scerts\mytest.com.pfx'
$password = ConvertTo-SecureString 'password' -AsPlainText -Force
$cert | Export-PfxCertificate -FilePath $certKeyPath -Password $password
$rootCert = $(Import-PfxCertificate -FilePath $certKeyPath -CertStoreLocation 'Cert:\LocalMachine\Root' -Password $password)

注意:

  • 需要使用Administrator模式打开PowerShell窗口
  • DnsName, CertKeyPath和 password的内容都可根据需求进行调整

 

 

第二步:准备两种读取证书的 .NET代码

方式一:通过证书文件名和密码读取加载证书

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)
               throw new Exception($"Certificate with thumbprint {certThumbprint} was not found");
               return cert.ToString();
           }
       }
       catch (Exception ex) { return ex.Message; }
   }

在本次实验中,通过API来调用以上 LoadPfx 和 FindPfx 方法

 

第三步:发布测试应用到Azure App Service

步骤参考发布 Web 应用:https://docs.azure.cn/zh-cn/app-service/quickstart-dotnetcore?tabs=net70&pivots=development-environment-vs#2-publish-your-web-app

 

第四步:测试接口并修复问题

通过文件方式读取证书内容,测试成功

但是,通过指纹查找的时候,却返回无法找到证书。

Certificate with thumbprint 5A1E7923F5638549F4BA3E29EEDBBDCB2E9B572E was not found

这是原因有两种:

1)证书没有添加到App Service的Certificates中。

2)需要在App Service的Configuration中添加配置WEBSITE_LOAD_CERTIFICATES参数,值为 * 或者是固定的 证书指纹值。

检查以上两点原因后,再次通过指纹方式查找证书。成功!

示例代码

1 using Microsoft.AspNetCore.Mvc;
 2 using System.Security.Cryptography.X509Certificates;
 3
 4 var builder = WebApplication.CreateBuilder(args);
 5
 6 // Add services to the container.
 7
 8 var app = builder.Build();
 9
10 // Configure the HTTP request pipeline.
11
12 app.UseHttpsRedirection();
13
14
15 app.MapGet("/loadpfxbyname", ([FromQuery(Name = "name")] string filename, [FromQuery(Name = "pwd")] string pwd) =>
16 {
17     var content = pfxTesting.LoadPfx(filename, pwd);
18     return content;
19 });
20
21 app.MapGet("/loadpfx/{pwd}", (string pwd) =>
22 {
23
24     var content = pfxTesting.LoadPfx(null, pwd);
25     return content;
26 });
27
28 app.MapGet("/findpfx/{certThumbprint}", (string certThumbprint) =>
29 {
30
31     var content = pfxTesting.FindPfx(certThumbprint);
32     return content;
33 });
34
35 app.Run();
36
37 class pfxTesting
38 {
39     public static string LoadPfx(string? filename, string password = "")
40     {
41         try
42         {
43             if (filename == null) filename = "contoso.com.pfx";
44
45             var bytes = File.ReadAllBytes(filename);
46             var cert = new X509Certificate2(bytes, password);
47
48             return cert.ToString();
49         }
50         catch (Exception ex)
51         {
52             return ex.Message;
53         }
54     }
55
56     public static string FindPfx(string certThumbprint = "")
57     {
58         try
59         {
60             bool validOnly = false;
61             using (X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))
62             {
63                 certStore.Open(OpenFlags.ReadOnly);
64
65                 X509Certificate2Collection certCollection = certStore.Certificates.Find(
66                                             X509FindType.FindByThumbprint,
67                                             // Replace below with your certificate's thumbprint
68                                             certThumbprint,
69                                             validOnly);
70                 // Get the first cert with the thumbprint
71                 X509Certificate2 cert = certCollection.OfType<X509Certificate2>().FirstOrDefault();
72
73                 if (cert is null)
74                     throw new Exception($"Certificate with thumbprint {certThumbprint} was not found");
75
76                 return cert.ToString();
77
78             }
79         }
80         catch (Exception ex) { return ex.Message; }
81     }
82 }

 

参考资料

发布 Web 应用:https://docs.azure.cn/zh-cn/app-service/quickstart-dotnetcore?tabs=net70&pivots=development-environment-vs#2-publish-your-web-app

生成自签名证书概述  https://learn.microsoft.com/zh-cn/dotnet/core/additional-tools/self-signed-certificates-guide#with-powershell

在 Azure 应用服务中通过代码使用 TLS/SSL 证书 : https://docs.azure.cn/zh-cn/app-service/configure-ssl-certificate-in-code#load-certificate-from-file

 

[END]

相关文章
|
6月前
|
存储 安全 Linux
【Azure App Service】在App Service中查看CA证书
在 Azure App Service 中,使用自签名或私有 CA 证书的远程服务可能会导致 SSL 握手失败。解决方法包括使用受信任 CA 签发的证书,或通过 App Service Environment 加载自定义根证书,实现安全连接。
155 3
|
5月前
|
移动开发 小程序 Android开发
基于 uni-app 开发的废品回收类多端应用功能与界面说明
本文将对一款基于 uni-app 开发的废品回收类多端应用,从多端支持范围、核心功能模块及部分界面展示进行客观说明,相关资源信息也将一并呈现。
198 0
|
7月前
|
域名解析 网络协议 API
【Azure Container App】配置容器应用的缩放规则 Managed Identity 连接中国区 Azure Service Bus 问题
本文介绍了在 Azure Container Apps 中配置基于自定义 Azure Service Bus 的自动缩放规则时,因未指定云环境导致的域名解析错误问题。解决方案是在扩展规则中添加 `cloud=AzureChinaCloud` 参数,以适配中国区 Azure 环境。内容涵盖问题描述、原因分析、解决方法及配置示例,适用于使用 KEDA 实现事件驱动自动缩放的场景。
171 1
|
4月前
|
Java 应用服务中间件 API
【App Service】部署War包到Azure云上遇404错误
Java应用部署至Azure App Service for Windows后报404,本地运行正常。经排查,日志提示类文件版本不兼容:应用由Java 17(class file version 61.0)编译,但环境仅支持到Java 11(55.0)。错误根源为Java版本不匹配。调整App Service的Java版本至17后问题解决,成功访问接口。
223 1
|
4月前
|
存储 Linux 网络安全
【Azure App Service】Root CA on App Service
Azure App Service for Windows应用连接外部SSL服务时,需确保其证书由受信任的根CA颁发。多租户环境下无法修改根证书,但ASE(单租户)可加载自定义CA证书。若遇证书信任问题,可更换为公共CA证书或将应用部署于ASE并导入私有CA证书。通过Kudu的PowerShell(Windows)或SSH(Linux)可查看当前受信任的根证书列表。
126 13
|
5月前
|
安全 算法 网络安全
SSL/TLS协议如何确保HTTP通信的安全
通过这些机制和过程,SSL/TLS对HTTP通信提供了强大的保护,确保数据不被未授权的第三方访问或篡改,这对维护数据隐私和网络安全至关重要。随着互联网技术的不断进步,SSL/TLS协议本身也在不断更新和升级,以对抗新出现的威胁和满足现代网络的要求。
323 10
|
5月前
|
网络协议 Java Linux
【App Service】在Azure环境中如何查看App Service实例当前的网络连接情况呢?
在 Azure App Service(Windows 和 Linux)中部署应用时,分析网络连接状态是排查异常、验证端口监听及确认后端连接的关键。本文介绍如何在 Linux 环境中使用 `netstat` 命令查看特定端口(如 443、3306、6380)的连接情况,并解析输出结果。同时说明在 Windows App Service 中 `netstat` 被禁用的情况下,如何通过门户抓包等替代方法进行网络诊断。内容涵盖命令示例、操作步骤及附录说明,帮助开发者快速掌握云环境中的网络分析技巧。
156 11
|
6月前
|
网络协议 关系型数据库 Linux
【App Service Linux】在Linux App Service中安装 tcpdump 并抓取网络包
在App Service for Linux环境中,无法像Windows一样直接使用网络排查工具抓包。本文介绍了如何通过TCPDUMP在Linux环境下抓取网络包,包括SSH进入容器、安装tcpdump、执行抓包命令及下载分析文件的完整操作步骤。
309 5
|
7月前
|
安全 应用服务中间件 网络安全
在Linux环境部署Flask应用并启用SSL/TLS安全协议
至此,你的Flask应用应该能够通过安全的HTTPS协议提供服务了。记得定期更新SSL证书,Certbot可以帮你自动更新证书。可以设定cronjob以实现这一点。
484 10
|
7月前
|
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文件解决该问题,镜像成功构建。
292 1