在使用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]

【Azure App Service】.NET代码实验App Service应用中获取TLS/SSL 证书 (App Service Windows)的更多相关文章

  1. 【Azure Developer】Python代码通过AAD认证访问微软Azure密钥保管库(Azure Key Vault)中机密信息(Secret)

    关键字说明 什么是 Azure Active Directory?Azure Active Directory(Azure AD, AAD) 是 Microsoft 的基于云的标识和访问管理服务,可帮 ...

  2. 在 Azure 中的 Linux 虚拟机上使用 SSL 证书保护 Web 服务器

    若要保护 Web 服务器,可以使用安全套接字层 (SSL) 证书来加密 Web 流量. 这些 SSL 证书可存储在 Azure Key Vault 中,并可安全部署到 Azure 中的 Linux 虚 ...

  3. 在 Azure 中的 Windows 虚拟机上使用 SSL 证书保护 IIS Web 服务器

    若要保护 Web 服务器,可以使用安全套接字层 (SSL) 证书来加密 Web 流量. 这些 SSL 证书可存储在 Azure Key Vault 中,并可安全部署到 Azure 中的 Windows ...

  4. 【转】【翻】Android Design Support Library 的 代码实验——几行代码,让你的 APP 变得花俏

    转自:http://mrfufufu.github.io/android/2015/07/01/Codelab_Android_Design_Support_Library.html [翻]Andro ...

  5. Android Design Support Library 的 代码实验——几行代码,让你的 APP 变得花俏

    原文:Codelab for Android Design Support Library used in I/O Rewind Bangkok session--Make your app fanc ...

  6. 搭建DAO层和Service层代码

    第一部分建立实体和映射文件 1 通过数据库生成的实体,此步骤跳过,关于如何查看生成反向工程实体类查看SSH框架搭建教程-反向工程章节 Tmenu和AbstractorTmenu是按照数据库表反向工程形 ...

  7. Kivy A to Z -- 怎样从python代码中直接訪问Android的Service

    在Kivy中,通过pyjnius扩展能够间接调用Java代码,而pyjnius利用的是Java的反射机制.可是在Python对象和Java对象中转来转去总让人感觉到十分别扭.好在android提供了b ...

  8. Azure AD Domain Service(二)为域服务中的机器配置 Azure File Share 磁盘共享

    一,引言 Azure File Share 是支持两种认证方式的! 1)Active Directory 2)Storage account key 记得上次分析的 "Azure File ...

  9. Express4.10.2开发框架中默认app.js的代码注释

    //通过require()加载了express.path等模块var express = require('express');var path = require('path');var favic ...

  10. 【Azure 存储服务】代码版 Azure Storage Blob 生成 SAS (Shared Access Signature: 共享访问签名)

    问题描述 在使用Azure存储服务,为了有效的保护Storage的Access Keys.可以使用另一种授权方式访问资源(Shared Access Signature: 共享访问签名), 它的好处可 ...

随机推荐

  1. el-tree选中子级时默认选中父级(角色授权)

    问题1:选中子级时默认选中父级 <el-tree :data="menuData" show-checkbox default-expand-all node-key=&qu ...

  2. 单元测试必备:Asp.Net Core代码覆盖率实战,打造可靠应用 !

    引言 在前几章我们深度讲解了单元测试和集成测试的基础知识,这一章我们来讲解一下代码覆盖率,代码覆盖率是单元测试运行的度量值,覆盖率通常以百分比表示,用于衡量代码被测试覆盖的程度,帮助开发人员评估测试用 ...

  3. 力扣551(java)-学生出勤记录Ⅰ(简单)

    题目: 给你一个字符串 s 表示一个学生的出勤记录,其中的每个字符用来标记当天的出勤情况(缺勤.迟到.到场).记录中只含下面三种字符: 'A':Absent,缺勤'L':Late,迟到'P':Pres ...

  4. 服务网格 ASM 年终总结:最终用户如何使用服务网格?

    ​简介:本文不打算回顾 Istio 或是阿里云服务网格 ASM 的变化或趋势,我们来聊一聊阿里云 ASM 服务网格,它的最终用户是如何使用服务网格的. 作者:叶剑宏 背景 阿里云服务网格 ASM 于 ...

  5. Spring Cloud Bus 消息总线介绍

    简介: 本文配套可交互教程已登录阿里云知行动手实验室,PC 端登录 start.aliyun.com 在浏览器中立即体验. 作者 | 洛夜来源 | 阿里巴巴云原生公众号 本文配套可交互教程已登录阿里云 ...

  6. dotnet 已知问题 使用 Directory.EnumerateXXX 方法枚举 C 盘根路径可能错误的问题

    在 dotnet 里面,可以使用 Directory.EnumerateXXX 系列方法进行枚举文件或文件夹.在准备枚举驱动器根路径的文件或文件夹时,可能获取到错误的路径.错误的步骤在于传入的是如 C ...

  7. webapp监听手机物理返回键,返回上一页面或者关闭app

    网上抄的做笔记: 1.项目下建文件夹commonFunction->physicBackListener.js 2.这个js文件内复制代码: document.addEventListener( ...

  8. CPU是什么?

    在程序是怎样跑起来的这本书中我们首先被询问的一个问题是"程序是什么?它是有什么组成的?而CPU又与程序有什么关系呢?",若我们能知道前两个,其实更容易将你带入讨论"CPU ...

  9. 使用 Splashtop 启用员工远程访问

    使员工进行远程工作似乎是一项耗时.不安全且昂贵的任务.但是,借助 Splashtop,您可以快速.轻松.安全地使您的员工从任何位置以最高 价值远程访问其工作站. ​ 如何使用 Splashtop 启用 ...

  10. C 语言编程 — 高级数据类型 — 枚举

    目录 文章目录 目录 前文列表 声明枚举类型 定义枚举类型的变量 枚举类型变量的枚举值 枚举在 switch 语句中的使用 将整型转换为枚举类型 前文列表 <程序编译流程与 GCC 编译器> ...