在 Azure 应用服务中通过代码使用 TLS/SSL 证书Use a TLS/SSL certificate in your code in Azure App Service

在应用程序代码中,可以访问已添加到应用服务的公用证书或私用证书In your application code, you can access the public or private certificates you add to App Service. 应用代码可以充当客户端并可访问需要证书身份验证的外部服务,否则可能需要执行加密任务。Your app code may act as a client and access an external service that requires certificate authentication, or it may need to perform cryptographic tasks. 本操作方法指南介绍如何在应用程序代码中使用公共或专用证书。This how-to guide shows how to use public or private certificates in your application code.

这种在代码中使用证书的方法利用应用服务中的 TLS 功能,要求应用位于“基本”层或更高层。This approach to using certificates in your code makes use of the TLS functionality in App Service, which requires your app to be in Basic tier or above. 如果应用位于“免费”或“共享”层,则你可以在应用存储库中包含证书文件If your app is in Free or Shared tier, you can include the certificate file in your app repository.

让应用服务管理 TLS/SSL 证书时,可以分开维护证书和应用程序代码,并保护敏感数据。When you let App Service manage your TLS/SSL certificates, you can maintain the certificates and your application code separately and safeguard your sensitive data.

先决条件Prerequisites

按照本操作方法指南操作:To follow this how-to guide:

查找指纹Find the thumbprint

Azure 门户的左侧菜单中,选择“应用程序服务” > “<app-name>” 。In the Azure portal, from the left menu, select App Services > <app-name>.

在应用的左侧导航栏中选择“TLS/SSL 设置”,然后选择“私钥证书(.pfx)”或“公钥证书(.cer)”。 From the left navigation of your app, select TLS/SSL settings, then select Private Key Certificates (.pfx) or Public Key Certificates (.cer).

找到要使用的证书并复制指纹。Find the certificate you want to use and copy the thumbprint.

复制证书指纹

使证书可供访问Make the certificate accessible

若要在应用代码中访问某个证书,请在 Azure CLI 中运行以下命令,将其指纹添加到 WEBSITE_LOAD_CERTIFICATES 应用设置:To access a certificate in your app code, add its thumbprint to the WEBSITE_LOAD_CERTIFICATES app setting, by running the following command in the Azure CLI:

az cloud set -n AzureChinaCloud
az webapp config appsettings set --name <app-name> --resource-group <resource-group-name> --settings WEBSITE_LOAD_CERTIFICATES=<comma-separated-certificate-thumbprints>

若要使所有证书可供访问,请将值设置为 *To make all your certificates accessible, set the value to *.

在 Windows 应用中加载证书Load certificate in Windows apps

Windows 证书存储中的 Windows 托管应用可以通过 WEBSITE_LOAD_CERTIFICATES 应用设置访问指定的证书,该存储的位置取决于定价层The WEBSITE_LOAD_CERTIFICATES app setting makes the specified certificates accessible to your Windows hosted app in the Windows certificate store, and the location depends on the pricing tier:

在 C# 代码中,可按证书指纹访问证书。In C# code, you access the certificate by the certificate thumbprint. 以下代码加载具有指纹 E661583E8FABEF4C0BEF694CBC41C28FB81CD870 的证书。The following code loads a certificate with the thumbprint E661583E8FABEF4C0BEF694CBC41C28FB81CD870.

using System;
using System.Linq;
using System.Security.Cryptography.X509Certificates;

string certThumbprint = "E661583E8FABEF4C0BEF694CBC41C28FB81CD870";
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<X509Certificate>().FirstOrDefault();

  if (cert is null)
      throw new Exception($"Certificate with thumbprint {certThumbprint} was not found");

  // Use certificate
  Console.WriteLine(cert.FriendlyName);
  
  // Consider to call Dispose() on the certificate after it's being used, avaliable in .NET 4.6 and later
}

在 Java 代码中,可以使用“使用者公用名”字段从“Windows-MY”存储访问证书。In Java code, you access the certificate from the "Windows-MY" store using the Subject Common Name field. 以下代码演示如何加载私钥证书:The following code shows how to load a private key certificate:

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.PrivateKey;

...
KeyStore ks = KeyStore.getInstance("Windows-MY");
ks.load(null, null); 
Certificate cert = ks.getCertificate("<subject-cn>");
PrivateKey privKey = (PrivateKey) ks.getKey("<subject-cn>", ("<password>").toCharArray());

// Use the certificate and key
...

对于不支持或不充分支持 Windows 证书存储的语言,请参阅从文件加载证书For languages that don't support or offer insufficient support for the Windows certificate store, see Load certificate from file.

从文件加载证书Load certificate from file

例如,如需加载手动上传的证书文件,则最好是使用 FTPS 而不是 Git 上传证书。If you need to load a certificate file that you upload manually, it's better to upload the certificate using FTPS instead of Git, for example. 应将专用证书之类的敏感信息置于源代码管理之外。You should keep sensitive data like a private certificate out of source control.

备注

即使从文件加载证书,Windows 上的 ASP.NET 和 ASP.NET Core 也必须访问证书存储。ASP.NET and ASP.NET Core on Windows must access the certificate store even if you load a certificate from a file. 若要在 Windows .NET 应用中加载证书文件,请在 Azure CLI 中使用以下命令加载当前用户配置文件:To load a certificate file in a Windows .NET app, load the current user profile with the following command in the Azure CLI:

az cloud set -n AzureChinaCloud
az webapp config appsettings set --name <app-name> --resource-group <resource-group-name> --settings WEBSITE_LOAD_USER_PROFILE=1

这种在代码中使用证书的方法利用应用服务中的 TLS 功能,要求应用位于“基本”层或更高层。This approach to using certificates in your code makes use of the TLS functionality in App Service, which requires your app to be in Basic tier or above.

以下 C# 示例从应用中的相对路径加载公用证书:The following C# example loads a public certificate from a relative path in your app:

using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;

...
var bytes = File.ReadAllBytes("~/<relative-path-to-cert-file>");
var cert = new X509Certificate2(bytes);

// Use the loaded certificate

若要了解如何从 Node.js、PHP、Python、Java 或 Ruby 文件加载 TLS/SSL 证书,请参阅适用于相应语言或 Web 平台的文档。To see how to load a TLS/SSL certificate from a file in Node.js, PHP, Python, Java, or Ruby, see the documentation for the respective language or web platform.

在 Linux/Windows 容器中加载证书Load certificate in Linux/Windows containers

WEBSITE_LOAD_CERTIFICATES 应用设置使指定的证书可作为文件供 Windows 或 Linux 容器应用(包括内置 Linux 容器)访问。The WEBSITE_LOAD_CERTIFICATES app settings makes the specified certificates accessible to your Windows or Linux container apps (including built-in Linux containers) as files. 这些文件位于以下目录中:The files are found under the following directories:

容器平台Container platform 公用证书Public certificates 私有证书Private certificates
Windows 容器Windows container C:\appservice\certificates\public C:\appservice\certificates\private
Linux 容器Linux container /var/ssl/certs /var/ssl/private

证书文件名是证书指纹。The certificate file names are the certificate thumbprints.

备注

应用服务将证书路径作为以下环境变量 WEBSITE_PRIVATE_CERTS_PATHWEBSITE_INTERMEDIATE_CERTS_PATHWEBSITE_PUBLIC_CERTS_PATHWEBSITE_ROOT_CERTS_PATH 注入到 Windows 容器中。App Service inject the certificate paths into Windows containers as the following environment variables WEBSITE_PRIVATE_CERTS_PATH, WEBSITE_INTERMEDIATE_CERTS_PATH, WEBSITE_PUBLIC_CERTS_PATH, and WEBSITE_ROOT_CERTS_PATH. 最好使用环境变量引用证书路径,而不是对证书路径进行硬编码,以防将来证书路径发生更改。It's better to reference the certificate path with the environment variables instead of hardcoding the certificate path, in case the certificate paths change in the future.

以下 C# 代码演示了如何在 Linux 应用中加载公共证书。The following C# code shows how to load a public certificate in a Linux app.

using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;

...
var bytes = File.ReadAllBytes("/var/ssl/certs/<thumbprint>.der");
var cert = new X509Certificate2(bytes);

// Use the loaded certificate

若要了解如何从 Node.js、PHP、Python、Java 或 Ruby 文件加载 TLS/SSL 证书,请参阅适用于相应语言或 Web 平台的文档。To see how to load a TLS/SSL certificate from a file in Node.js, PHP, Python, Java, or Ruby, see the documentation for the respective language or web platform.

更多资源More resources