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

相关文章
|
2天前
|
安全 算法 网络协议
解析:HTTPS通过SSL/TLS证书加密的原理与逻辑
HTTPS通过SSL/TLS证书加密,结合对称与非对称加密及数字证书验证实现安全通信。首先,服务器发送含公钥的数字证书,客户端验证其合法性后生成随机数并用公钥加密发送给服务器,双方据此生成相同的对称密钥。后续通信使用对称加密确保高效性和安全性。同时,数字证书验证服务器身份,防止中间人攻击;哈希算法和数字签名确保数据完整性,防止篡改。整个流程保障了身份认证、数据加密和完整性保护。
|
3月前
|
安全 网络安全 数据安全/隐私保护
SSL/TLS证书**是一种用于加密网络通信的数字证书
SSL/TLS证书**是一种用于加密网络通信的数字证书
172 6
|
3月前
|
安全 算法 网络安全
SSL/TLS协议是什么?
SSL/TLS协议是什么?
271 57
|
3月前
|
C# Windows
【Azure App Service】在App Service for Windows上验证能占用的内存最大值
根据以上测验,当使用App Service内存没有达到预期的值,且应用异常日志出现OutOfMemory时,就需要检查Platform的设置是否位64bit。
67 11
|
3月前
|
缓存 安全 算法
SSL和TLS部署实践
在TLS中,所有安全性都以服务器的加密身份开始,这就需要一个强大的私钥来防止攻击者进行模拟攻击。同样重要的是拥有一个有效和强大的证书,它会授予私钥来代表一个特定的主机名。
100 2
|
3月前
|
开发框架 监控 .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
|
3月前
|
存储 安全 算法
SSL和TLS部署实践
【10月更文挑战第28天】在TLS中,服务器的加密身份和强大私钥是安全基础,2048位RSA密钥足以满足大多数需求。保护私钥需在可信环境生成、加密存储、使用HSM、及时撤销旧证书、每年更新证书。确保证书覆盖所有域名,选择可靠CA,使用SHA256签名算法,配置完整证书链,禁用不安全加密套件,启用前向保密,使用会话重用机制,启用OCSP Stapling,加密整个网站,删除混合内容,安全设置Cookie,配置HSTS和CSP。
368 1
|
4月前
|
安全 网络安全 数据安全/隐私保护
【Azure Developer】System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
|
4月前
|
JavaScript 安全 Java
谈谈UDP、HTTP、SSL、TLS协议在java中的实际应用
下面我将详细介绍UDP、HTTP、SSL、TLS协议及其工作原理,并提供Java代码示例(由于Deno是一个基于Node.js的运行时,Java代码无法直接在Deno中运行,但可以通过理解Java示例来类比Deno中的实现)。
128 1

热门文章

最新文章