在使用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. 动态规划(五)——坐标dp

    传纸条 题目描述 小渊和小轩是好朋友也是同班同学,他们在一起总有谈不完的话题.一次素质拓展活动中,班上同学安排做成一个m行n列的矩阵, 而小渊和小轩被安排在矩阵对角线的两端,因此,他们就无法直接交谈了 ...

  2. ​CentOS防火墙操作命令 ​

    CentOS防火墙操作命令 1.查看防火墙服务状态 systemctl status firewalld.service 或者查看防火墙的状态: 1 firewall-cmd --state 2.开启 ...

  3. 前端vue+elementUI如何实现记住密码功能

    我们这回使用纯前端保存密码 既然是记住密码,前端也就是使用cookie保存,访问时用cookie读取 先来了解下cookie的基本使用吧 Cookie 所有的cookie信息都在document.co ...

  4. CentOS升级内核-- CentOS9 Stream/CentOS8 Stream/CentOS7

    官方文档在此 升级原因 当我们安装一些软件(对,我说的就是Kubernetes),可能需要新内核的支持,而CentOS又比较保守,不太升级,所以需要我们手工升级. # 看下目前是什么版本内核 unam ...

  5. Jedis连接踩坑日记

    Jedis连接踩坑日记 背景: 线上某块业务的增删改功能全部都不可用.页面发送了xhr请求之后 状态一直处于pending状态,后端没有日志产生 排查路线与解决办法 第一:由于服务在内网里面,无法进行 ...

  6. 文本溢出显示省略号css

    项目中常常有这种需要我们对溢出文本进行"..."显示的操作,单行多行的情况都有(具体几行得看设计师心情了),这篇随笔是我个人对这种情况解决办法的归纳,欢迎各路英雄指教. 单行 语法 ...

  7. Linux下的权限(角色,文件权限)

    目录 1.什么是权限 2.文件类型及权限 ①Linux文件类型: ②剩余9个字符对应的含义: ③文件权限值的表示方法(进制法) 3.如何操作权限 3.1改变权限的命令操作 chmod #change ...

  8. 力扣34(java)-在排序数组中查找元素的第一个和最后一个位置(中等)

    题目: 给你一个按照非递减顺序排列的整数数组 nums,和一个目标值 target.请你找出给定目标值在数组中的开始位置和结束位置. 如果数组中不存在目标值 target,返回 [-1, -1]. 你 ...

  9. OpenTK 入门 初始化窗口

    本文属于 OpenTK 入门博客,这是一项使用 C# 做底层调用 OpenGL 和 OpenAL 和 OpenCL 的技术.但值得一提的是,如果是想做渲染相关的话,当前是不建议使用 OpenGL 的, ...

  10. 3.Exporter概述

    一.Exporter概述 所有可以向Prometheus提供监控样本数据的程序都可以被称为一个Exporter.而Exporter的一个实例称为target,如下所示,Prometheus通过轮询的方 ...