使用 OWIN 在 Azure Web App 中获取客户端证书

Getting client certificates in Azure Web App using OWIN

如果您使用 Azure Web Apps 来托管您的 Web 应用程序(让它成为一个 ASP.NET MVC Web 应用程序),您 do not have the possibility 在 Azure Web Apps 后面设置 IIS 以接受客户端通过 HTTPS 连接的证书。我的应用程序有一些 Web API 端点,只有当用户拥有正确的证书和允许的指纹时才能访问这些端点。但是,我还有其他端点(当然还有网站),无需客户端证书即可访问。所以在我的例子中,唯一的方法是接受客户端证书。

我不确定,但如果我很清楚,我仍然可以在 IIS 中的 SSL 设置设置为忽略时使用 OWIN 获取客户端证书。如果我使用 OWIN 并通过 OWIN 环境,我可以看到一个名为 ssl.LoadClientCertAsync.

的键

我正在实现第三方服务将调用的端点,因此我无法控制请求的内容。我知道有一个 ssl.ClientCertificate 密钥,类型为 X509Certificate,但在我的例子中这个密钥不存在。

我找到了一些关于使用此 ssl.LoadClientCertAsync 密钥获取证书的 C# 解决方案,例如 CheckClientCertificate 方法Katana or the solution in this C# Corner article。在我能在网上找到的每个解决方案中,作者都​​将这种类型作为 Func<Task> 获取,然后调用此任务,例如使用 await 运算符。

var certLoader = context.Get<Func<Task>>("ssl.LoadClientCertAsync");
if (certLoader != null)
{
     await certLoader();
...

之后,他们使用 ssl.ClientCertificate 密钥检索证书。

    var asyncCert = context.Get<X509Certificate>("ssl.ClientCertificate");

在此示例中,我的 asyncCert 变量始终为空。 OWIN 上下文中没有任何 ssl.ClientCertificate 键。我尝试使用 X509Certificate2 而不是 X509Certificate,但我仍然得到空值。

我的问题是,当默认 SSL 设置为忽略时,是否可以使用 OWIN 在 Azure 网站中获取客户端证书?如果是,为什么我不能使用 ssl.LoadClientCertAsync 密钥获取证书?

根据您的描述,我已经创建了 ASP.NET MVC Web 应用程序以在 OWIN 中使用客户端证书来检查此问题。以下代码可以在我的本地运行:

if (Request.GetOwinContext().Environment.Keys.Contains(_owinClientCertKey))
{
    X509Certificate2 clientCert = Request.GetOwinContext().Get<X509Certificate2>(_owinClientCertKey);
    return Json(new { Thumbprint = clientCert.Thumbprint, Issuer = clientCert.Issuer }, JsonRequestBehavior.AllowGet);
}
else
    return Content("There's no client certificate attached to the request.");

对于设置为 接受 的 SSL 设置,我可以 select 一个证书或取消window select 一个证书的弹出窗口。

据我所知,我们可以通过将 clientCertEnabled 设置为 true 来启用客户端证书身份验证,此设置等同于 IIS 中的 SSL 设置要求选项。

How To Configure TLS Mutual Authentication for Web App 所述,关于从您的 Web 应用程序访问客户端证书:

If you are using ASP.NET and configure your app to use client certificate authentication, the certificate will be available through the HttpRequest.ClientCertificate property. For other application stacks, the client cert will be available in your app through a base64 encoded value in the X-ARR-ClientCert request header.

My question is is it possible to get the client certificate in an Azure Web Site while the default SSL setting is Ignore by using OWIN?

据我所知,客户端证书的当前 SSL 设置目前仅支持 IgnoreRequire。在 azure web 应用程序上托管您的 web 应用程序时,对于使用客户端证书身份验证访问您的 azure web 应用程序的客户端用户,他们可以在向您的 azure 发送请求时将证书指定为 base64 编码值作为您的自定义请求 header Web 应用程序,然后您可以尝试检索 header 并验证证书(如果证书自定义请求 header 存在)。详情可以关注这个sample.

此外,您可以使用 Azure VM 或 Azure 云服务而不是 azure web 应用程序,此时您可以完全控制 IIS 中的 SSL 设置。