【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]

相关文章
|
3月前
|
JSON 数据格式
【Azure Fabric Service】演示使用PowerShell命令部署SF应用程序(.NET)
本文详细介绍了在中国区微软云Azure上使用Service Fabrics服务时,通过PowerShell命令发布.NET应用的全过程。由于Visual Studio 2022无法直接发布应用,需借助PowerShell脚本完成部署。文章分三步讲解:首先在Visual Studio 2022中打包应用部署包,其次连接SF集群并上传部署包,最后注册应用类型、创建实例并启动服务。过程中涉及关键参数如服务器证书指纹和服务端证书指纹的获取,并附带图文说明,便于操作。参考官方文档,帮助用户成功部署并运行服务。
153 72
|
3月前
|
算法 应用服务中间件 网络安全
阿里云WoSign“国密RSA双SSL证书”应用实践
阿里云WoSign品牌SSL证书是阿里云平台热销的国产品牌证书之一,支持签发国密合规的SM2算法SSL证书以及全球信任的RSA算法SSL证书,能够满足平台用户不同的SSL证书应用需求,同时为用户提供国密模块支持,实现“国密/RSA双证书部署”。
492 6
阿里云WoSign“国密RSA双SSL证书”应用实践
|
3月前
|
存储 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对象,实现通过自定义域名访问存储服务。
|
6月前
|
安全 小程序 数据建模
SSL证书概述、类型、价格、作用及应用等10大常见问题解答
在互联网+时代,随着数字化进程加速,网络威胁日益严峻。SSL证书作为遵循SSL协议的数字证书,能实现HTTPS加密,验证网站服务器身份,确保数据传输安全性和完整性,有效防范中间人攻击和钓鱼网站。本文将介绍关于SSL证书的10大常见问题,帮助您更好地了解和使用SSL证书,确保网站安全。
|
7月前
|
开发框架 监控 .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
115 5
|
8月前
|
JavaScript 安全 Java
谈谈UDP、HTTP、SSL、TLS协议在java中的实际应用
下面我将详细介绍UDP、HTTP、SSL、TLS协议及其工作原理,并提供Java代码示例(由于Deno是一个基于Node.js的运行时,Java代码无法直接在Deno中运行,但可以通过理解Java示例来类比Deno中的实现)。
175 1
|
2月前
|
人工智能 JSON 小程序
【一步步开发AI运动APP】七、自定义姿态动作识别检测——之规则配置检测
本文介绍了如何通过【一步步开发AI运动APP】系列博文,利用自定义姿态识别检测技术开发高性能的AI运动应用。核心内容包括:1) 自定义姿态识别检测,满足人像入镜、动作开始/停止等需求;2) Pose-Calc引擎详解,支持角度匹配、逻辑运算等多种人体分析规则;3) 姿态检测规则编写与执行方法;4) 完整示例展示左右手平举姿态检测。通过这些技术,开发者可轻松实现定制化运动分析功能。
|
27天前
|
存储 消息中间件 前端开发
PHP后端与uni-app前端协同的校园圈子系统:校园社交场景的跨端开发实践
校园圈子系统校园论坛小程序采用uni-app前端框架,支持多端运行,结合PHP后端(如ThinkPHP/Laravel),实现用户认证、社交关系管理、动态发布与实时聊天功能。前端通过组件化开发和uni.request与后端交互,后端提供RESTful API处理业务逻辑并存储数据于MySQL。同时引入Redis缓存热点数据,RabbitMQ处理异步任务,优化系统性能。核心功能包括JWT身份验证、好友系统、WebSocket实时聊天及活动管理,确保高效稳定的用户体验。
106 4
PHP后端与uni-app前端协同的校园圈子系统:校园社交场景的跨端开发实践
|
1月前
|
人工智能 JavaScript 前端开发
借助 CodeBuddy,我轻松开发出三分钟读书 App
借助 CodeBuddy,我轻松开发出三分钟读书 App
51 6
|
1月前
|
人工智能 小程序 API
【一步步开发AI运动APP】九、自定义姿态动作识别检测——之关键点追踪
本文介绍了【一步步开发AI运动APP】系列中的关键点追踪技术。此前分享的系列博文助力开发者打造了多种AI健身场景的小程序,而新系列将聚焦性能更优的AI运动APP开发。文章重点讲解了“关键点位变化追踪”能力,适用于动态运动(如跳跃)分析,弥补了静态姿态检测的不足。通过`pose-calc`插件,开发者可设置关键点(如鼻子)、追踪方向(X或Y轴)及变化幅度。示例代码展示了如何在`uni-app`框架中使用`createPointTracker`实现关键点追踪,并结合人体识别结果完成动态分析。具体实现可参考文档与Demo示例。