【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: 共享访问签名), 它的好处可 ...
随机推荐
- docker 应用篇————容器共享数据卷[十五]
前言 简单介绍一下多个容器间容器卷共享. 正文 先启动上一节的test:2.0 这个镜像. docker run --name test01 -it test:2.0 /bin/bash 然后 ctr ...
- ping 介绍
前言 因为要整理网络这一块,所以打算先把概念写下.这节介绍ping的实现原理. 正文 先看一下图: 又没有发现和我们的icmp很像?对头.在icmp中,我写道:icmp有两种报文,一种是差错报文,一种 ...
- 【笔记】Java相关大杂烩②
[笔记]Java相关大杂烩② if单分支情况下,如果没有加 {},那么默认只包含第一条语句. if 和 else 分支后面如果包含多条语句,那么需要使用 {} 括起来. 不能随意地使用数学上的表达方式 ...
- 力扣451(java)-根据字符出现频率排序(中等)
题目: 给定一个字符串 s ,根据字符出现的 频率 对其进行 降序排序 .一个字符出现的 频率 是它出现在字符串中的次数. 返回 已排序的字符串 .如果有多个答案,返回其中任何一个. 示例 1: 输入 ...
- HarmonyOS NEXT应用开发——Navigation开发 页面切换场景范例
简介 在应用开发时,我们常常遇到,需要在应用内多页面跳转场景时中使用Navigation导航组件做统一的页面跳转管理,它提供了一系列属性方法来设置页面的标题栏.工具栏以及菜单栏的各种展示样式.除此之外 ...
- 现代斗山X瓴羊:“一横四纵“解决方案聚焦中台场景级部署
简介: 经过充分的调研后,现代斗山IT团队和业务团队,与瓴羊数据中台项目组一起完成了涵盖客户.商机.设备等多层面的问题梳理及痛点分析,并借助于瓴羊Dataphin+Quick BI+Quick Aud ...
- 博时基金基于 RocketMQ 的互联网开放平台 Matrix 架构实践
简介: Matrix 经过一年多的建设,目前已具备多渠道统一接入.第三方生态互联互通.基金特色交易场景化封装等功能特性.Matrix 通过建设有品质.有温度的陪伴,从技术上和体验上,让用户理解风险,理 ...
- 形式化验证工具TLA+:程序员视角的入门之道
简介: 女娲是飞天分布式系统中提供分布式协同的基础服务,支撑着阿里云的计算.网络.存储等几乎所有云产品.在女娲分布式协同服务中,一致性引擎是核心基础模块,支持了Paxos,Raft,EPaxos等多 ...
- [php-src] Php内核的有趣高频宏
内容均以php-5.6.14为例. 1. EXPECTED 和 UNEXPECTED 宏,用在判断条件的时候. ./Zend/zend.h:390 #if (defined (__GNUC__) &a ...
- K8s集群中部署SpringCloud在线购物平台(一)
一.安装k8s高可用集群 主机名 IP 配置 网络 master控制节点 192.168.10.10 centos 7.9 4核4G 桥接 node1工作节点 192.168.10.11 centos ...