問題描述
.NET 6 MVC應用,程式碼中要求客戶端訪問時候必須攜帶正確的證書,如果不攜帶或者攜帶錯誤的證書,都會得到 HTTP ERROR 403 Forbidden 錯誤
在App Service中,客戶端訪問不攜帶證書時的錯誤頁面為
在App Service中客戶端訪問攜帶了證書,但是證書驗證失敗的錯誤頁面為
問題解決
在App Service的配置頁面 (General Settings)中,可以開啟Client Certificate Mode為Require(它的預設值為Ignore)。這樣在第一次訪問時候,客戶端會要求從本地選擇一個客戶端證書。
配置截圖
當訪問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/