天天看點

【Azure 應用服務】應用代碼需要用戶端證書進行驗證,部署到App Service後,如何配置讓用戶端攜帶證書呢?

問題描述

.NET 6 MVC應用,代碼中要求用戶端通路時候必須攜帶正确的證書,如果不攜帶或者攜帶錯誤的證書,都會得到 HTTP ERROR 403 Forbidden 錯誤

在App Service中,用戶端通路不攜帶證書時的錯誤頁面為

【Azure 應用服務】應用代碼需要用戶端證書進行驗證,部署到App Service後,如何配置讓用戶端攜帶證書呢?

在App Service中用戶端通路攜帶了證書,但是證書驗證失敗的錯誤頁面為

【Azure 應用服務】應用代碼需要用戶端證書進行驗證,部署到App Service後,如何配置讓用戶端攜帶證書呢?

問題解決

在App Service的配置頁面 (General Settings)中,可以開啟Client Certificate Mode為Require(它的預設值為Ignore)。這樣在第一次通路時候,用戶端會要求從本地選擇一個用戶端證書。

配置截圖

【Azure 應用服務】應用代碼需要用戶端證書進行驗證,部署到App Service後,如何配置讓用戶端攜帶證書呢?

當通路App Service時,浏覽器就會自動彈出選擇證書視窗:

【Azure 應用服務】應用代碼需要用戶端證書進行驗證,部署到App Service後,如何配置讓用戶端攜帶證書呢?

代碼參考

驗證用戶端上傳證書的 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.1:https://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/

當在複雜的環境中面臨問題,格物之道需:濁而靜之徐清,安以動之徐生。 雲中,恰是如此!

繼續閱讀