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

相关文章
|
14天前
|
安全 算法 网络协议
解析:HTTPS通过SSL/TLS证书加密的原理与逻辑
HTTPS通过SSL/TLS证书加密,结合对称与非对称加密及数字证书验证实现安全通信。首先,服务器发送含公钥的数字证书,客户端验证其合法性后生成随机数并用公钥加密发送给服务器,双方据此生成相同的对称密钥。后续通信使用对称加密确保高效性和安全性。同时,数字证书验证服务器身份,防止中间人攻击;哈希算法和数字签名确保数据完整性,防止篡改。整个流程保障了身份认证、数据加密和完整性保护。
|
4月前
|
安全 网络安全 数据安全/隐私保护
SSL/TLS证书**是一种用于加密网络通信的数字证书
SSL/TLS证书**是一种用于加密网络通信的数字证书
185 6
|
4月前
|
边缘计算 C++ 开发者
.NET 9 中没有 wasi 实验性支持
【11月更文挑战第2天】.NET 9 引入了对 WASI(WebAssembly System Interface)的实验性支持。WASI 扩展了 WebAssembly 的使用场景,使其不仅限于浏览器,还能在服务器端和边缘计算等环境中运行。.NET 9 的 WASI 支持包括构建可在 WASI 环境下运行的应用程序、增强与其他 WASI 模块的互操作性,以及针对 WASI 环境进行性能优化。
|
7天前
|
安全 算法 网络安全
SSL/TLS:构建数字世界的加密长城
**协议演进:从网景实验室到全球标准** 1994年,网景公司推出SSL协议,首次实现40位密钥加密传输,开启网络安全新纪元。此后,SSL 3.0、TLS 1.0相继问世,至2018年TLS 1.3将握手速度提升60%,强制前向加密确保历史会话安全。TLS协议通过非对称加密、对称加密和证书信任链等多层架构保障通信安全。2014年POODLE漏洞促使全行业禁用SSL 3.0,催生防降级机制。
|
11天前
|
安全 算法 物联网
SSL/TLS:互联网通信的加密基石与安全实践
**简介:** 在数字化时代,互联网每天传输海量敏感数据,网络攻击频发。SSL/TLS协议作为网络安全的基石,通过加密技术确保数据安全传输。本文解析SSL/TLS的技术架构、密码学原理、应用场景及常见误区,探讨其在未来的发展趋势,强调持续演进以应对新型威胁的重要性。 SSL/TLS不仅保障Web安全,还广泛应用于API、邮件、物联网等领域,并遵循合规标准如PCI DSS和GDPR。
|
9天前
|
存储 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对象,实现通过自定义域名访问存储服务。
|
2月前
|
开发框架 安全 .NET
【Azure Developer】.NET Aspire 项目本地调试遇 Grpc.Core.RpcException 异常( Error starting gRPC call ... )
Error starting gRPC call. HttpRequestException: The SSL connection could not be established, see inner exception. AuthenticationException: The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot
67 12
|
4月前
|
安全 算法 网络安全
SSL/TLS协议是什么?
SSL/TLS协议是什么?
294 57
|
4月前
|
开发框架 监控 .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

热门文章

最新文章