【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

第四步:测试接口并修复问题
通过文件方式读取证书内容,测试成功

但是,通过指纹查找的时候,却返回无法找到证书。
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 }
参考资料
在 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)的更多相关文章
- 【Azure Developer】Python代码通过AAD认证访问微软Azure密钥保管库(Azure Key Vault)中机密信息(Secret)
关键字说明 什么是 Azure Active Directory?Azure Active Directory(Azure AD, AAD) 是 Microsoft 的基于云的标识和访问管理服务,可帮 ...
- 在 Azure 中的 Linux 虚拟机上使用 SSL 证书保护 Web 服务器
若要保护 Web 服务器,可以使用安全套接字层 (SSL) 证书来加密 Web 流量. 这些 SSL 证书可存储在 Azure Key Vault 中,并可安全部署到 Azure 中的 Linux 虚 ...
- 在 Azure 中的 Windows 虚拟机上使用 SSL 证书保护 IIS Web 服务器
若要保护 Web 服务器,可以使用安全套接字层 (SSL) 证书来加密 Web 流量. 这些 SSL 证书可存储在 Azure Key Vault 中,并可安全部署到 Azure 中的 Windows ...
- 【转】【翻】Android Design Support Library 的 代码实验——几行代码,让你的 APP 变得花俏
转自:http://mrfufufu.github.io/android/2015/07/01/Codelab_Android_Design_Support_Library.html [翻]Andro ...
- Android Design Support Library 的 代码实验——几行代码,让你的 APP 变得花俏
原文:Codelab for Android Design Support Library used in I/O Rewind Bangkok session--Make your app fanc ...
- 搭建DAO层和Service层代码
第一部分建立实体和映射文件 1 通过数据库生成的实体,此步骤跳过,关于如何查看生成反向工程实体类查看SSH框架搭建教程-反向工程章节 Tmenu和AbstractorTmenu是按照数据库表反向工程形 ...
- Kivy A to Z -- 怎样从python代码中直接訪问Android的Service
在Kivy中,通过pyjnius扩展能够间接调用Java代码,而pyjnius利用的是Java的反射机制.可是在Python对象和Java对象中转来转去总让人感觉到十分别扭.好在android提供了b ...
- Azure AD Domain Service(二)为域服务中的机器配置 Azure File Share 磁盘共享
一,引言 Azure File Share 是支持两种认证方式的! 1)Active Directory 2)Storage account key 记得上次分析的 "Azure File ...
- Express4.10.2开发框架中默认app.js的代码注释
//通过require()加载了express.path等模块var express = require('express');var path = require('path');var favic ...
- 【Azure 存储服务】代码版 Azure Storage Blob 生成 SAS (Shared Access Signature: 共享访问签名)
问题描述 在使用Azure存储服务,为了有效的保护Storage的Access Keys.可以使用另一种授权方式访问资源(Shared Access Signature: 共享访问签名), 它的好处可 ...
随机推荐
- 鸿蒙HarmonyOS实战-ArkUI组件(页面路由)
一.路由导航 路由导航是指在应用程序中通过路径导航定位到特定页面的过程.路由导航的实现通常采用路由器(router)来进行管理,路由器根据路径的不同值将用户请求导向到不同的页面. 在HarmonyOS ...
- 2款Notepad++平替工具(实用、跨平台的文本编辑器)
前言 今天大姚给大家分享2款Notepad++平替工具,实用.跨平台(支持Window/MacOS/Linux操作系统平台)的文本编辑器. NotepadNext NotepadNext是一个跨平台的 ...
- nginx重新整理——————分析log数据[六]
前言 简单介绍一下goaccess. 正文 安装: yum install epel-release yum install GeoIP GeoIP-devel GeoIP-data yum inst ...
- spring boot @propertySource @importResource @Bean [六]
@propertySource 指定property的配置源. 创建一个person.property: 然后修改person注解; 在运行test之后,结果为: @importResource 这个 ...
- arp 的基础概念
前言 打算整理网络这一块,先把概念写完. 就是有一个问题,那就是为什么有ip地址还有mac地址呢? 原因是这样子的,我们知道ip协议是第三层,那么有一个问题了,如果只有第三层的ip是否能过识别到主机? ...
- Lattice下载器高速编程器HW-USBN-2B fpga仿真器ispdown烧录器
1.概述 HW-USBN-2B 编程烧录Lattice所有芯片,速度非常快.支持Lattice FPGA芯片在线稳定仿真.烧录.加密,支持Lattice CPLD烧录.支持外部配置FLASH.PROM ...
- vue3.0 中文文档(暂时)地址
https://v3.cn.vuejs.org/ https://vue-docs-next-zh-cn.netlify.app/guide/installation.html#vue-devtool ...
- Linux基础-01:Linux命令的基本格式
2.1.1 命令提示符 在CentOS 7操作系统中,Linux命令提示符就像是你与电脑交流的一个小标志,告诉你系统已经准备好接受你的指令了. 它通常会显示在你打开的终端窗口或控制台的最前面. 让我们 ...
- 力扣524(java)-通过删除字母匹配到字典里最长单词(中等)
题目: 给你一个字符串 s 和一个字符串数组 dictionary ,找出并返回 dictionary 中最长的字符串,该字符串可以通过删除 s 中的某些字符得到. 如果答案不止一个,返回长度最长且字 ...
- 使用MaxCompute LOAD命令批量导入OSS数据最佳实践—STS方式LOAD开启KMS加密OSS数据
简介: MaxCompute使用load overwrite或load into命令将外部存储的数据(如:oss)导入到MaxCompute前的授权操作. MaxCompute使用load overw ...