【Azure 应用服务】应用代码需要客户端证书进行验证,部署到App Service后,如何配置让客户端携带证书呢? - LuBu0505/My-Code GitHub Wiki

问题描述

.NET 6 MVC应用,代码中要求客户端访问时候必须携带正确的证书,如果不携带或者携带错误的证书,都会得到 HTTP ERROR 403 Forbidden 错误

在App Service中,客户端访问不携带证书时的错误页面为

image

在App Service中客户端访问携带了证书,但是证书验证失败的错误页面为

image

问题解决

在App Service的配置页面 (General Settings)中,可以开启Client Certificate Mode为Require(它的默认值为Ignore)。这样在第一次访问时候,客户端会要求从本地选择一个客户端证书。

配置截图

image 当访问App Service时,浏览器就会自动弹出选择证书窗口: image

代码参考

验证客户端上传证书的 Thumbprints 的片段代码

builder.Services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)
        .AddCertificate(options => {
            options.AllowedCertificateTypes = CertificateTypes.All;

            options.Events = new CertificateAuthenticationEvents
            {
                OnCertificateValidated = context => { string[] allowedThumbprints = { "9bded811e9852f3cb6b347529f78b1f4be5bcf50", "5d6d791a9284628203a5b3e238e5ee7448d57f2b", "41b3906fa93c50d2cce35132d8853fdf29d7d539", "3109b0222269b47cd8190252f5f1adb06751103a" }; if (allowedThumbprints.Contains(context.ClientCertificate.Thumbprint.ToLower()))
                    {
                        context.Success();
                    } else {
                        context.Fail("Invalid certificate: " + context.ClientCertificate.Thumbprint);
                    } return Task.CompletedTask;
                },
                OnAuthenticationFailed = context => {
                    context.Fail("Invalid certificate"); return Task.CompletedTask;
                }
            };
        });

参考资料

Configure certificate authentication in ASP.NET Core: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/certauth?view=aspnetcore-6.0

CERTIFICATE AUTHENTICATION IN ASP.NET CORE 3.1https://damienbod.com/2019/06/13/certificate-authentication-in-asp-net-core-3-0/

Using Certificates For API Authentication In .NET 5: https://www.c-sharpcorner.com/article/using-certificates-for-api-authentication-in-net-5/

当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!

分类: 【Azure 应用服务】

标签: App ServiceAzure Developer配置让客户端携带证书HTTP ERROR 403 Forbidden