【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: 共享访问签名), 它的好处可 ...
随机推荐
- Linux(CentOS7.2)安装cnpm
1.安装cnpm npm install -g cnpm --registry=https://registry.npm.taobao.org 2.如下安装成功 /root/node-v10.16.3 ...
- 重新点亮shell————特殊符号[五]
前言 简单整理一下特殊符号. 正文 特殊符号大全: 引号 ' 完成引用 "" 不完全引用 ` 执行命令 括号 () (()) $() 圆括号 单独使用圆括号会产生一个子shell ...
- mysql 必知必会整理—视图[十二]
前言 简单整理一下视图. 正文 视图: 需要MySQL 5 MySQL 5添加了对视图的支持.因此,本章内容适用于MySQL 5及以后的版本. 视图是虚拟的表.与包含数据的表不一样,视图只包含使用时动 ...
- 鸿蒙HarmonyOS实战-ArkUI组件(Tabs)
一.Tabs Tabs组件是一种常见的用户界面(UI)组件,它是一个可以容纳多个选项卡的容器组件.每个选项卡通常包含一个面板和一个标签,用户可以通过点击标签来切换面板.Tabs组件通常用于展示多个相关 ...
- vue-manage-system 版本更新,让开发更加简单
vue-manage-system 近期进行了一次版本升级,主要是支持了更多功能.升级依赖版本和优化样式,并且上线了官方文档网站,大部分功能都有文档或者使用示例,更加适合新手上手开发,只需要根据实际业 ...
- 牛客网-SQL专项训练10
①SQL语句中与Having子句同时使用的语句是:group by 解析: SQL语法中,having需要与group by联用,起到过滤group by后数据的作用. ②下列说法错误的是?C 解析: ...
- 龙蜥正式开源 SysOM:百万级实战经验打造!一站式运维管理平台 | 龙蜥技术
简介:SysOM集监控.告警.诊断.修复.安全能力于一体的操作系统运维平台. 文/系统运维 SIG 如果你被突如其来的 OOPS 和满屏奇怪的函数弄得满头问号?机器内存明明很大,却申请不出来内存 ...
- 一款跑在云上的定制容器专属 OS 来了——LifseaOS | 龙蜥技术
简介:如果可以把运维 API 化,那我们是不是可以把 OS 也作为一个 K8S 可以管理的资源,让 K8S 像管理容器一样管理OS? 引言 在 2021 年 10 月的云栖大会上,为云原生而生的 ...
- [Auth] 浅谈 jwt token 的妙处
无状态(易扩展). 有过期时间限制,相对安全(可以有多个有效的 token). 更轻量(适合少量信息),类似传统 query string 签名方式. 标准统一(跨语言). Refer:JWT Aut ...
- [Blockchain] 前后端完全去中心化的思路, IPFS 与 Ethereum Contract
我们在使用智能合约的时候,一般是把它当成去中心.减少信任依赖的后端存在. 如果没有特殊后端功能要求,一个 DApp 只需要前端驱动 web3js 就可以实现了. 可以看到,现在前端部分依旧是一个中心化 ...