Blazor Server部署后OpenIdConnect认证失败问题求助
问题背景
本地使用本地证书时应用正常运行,部署到Azure门户后无法完成认证,反复弹出账户选择弹窗。已完成以下配置:
- Microsoft Entra ID应用注册
- 配置托管身份访问Key Vault
- 设置正确的返回URL
相关代码与配置
Program.cs
using CertificateAuth.Server.Components; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.Identity.Web; using Microsoft.Identity.Web.UI; var builder = WebApplication.CreateBuilder(args); builder.Services.AddRazorComponents() .AddInteractiveServerComponents() .AddInteractiveWebAssemblyComponents(); builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd")) .EnableTokenAcquisitionToCallDownstreamApi(new string[] { "User.Read", "User.Read.All" }) .AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph")) .AddInMemoryTokenCaches(); builder.Services.AddControllersWithViews() .AddMicrosoftIdentityUI(); builder.Services.AddAuthorization(options => { options.FallbackPolicy = options.DefaultPolicy; }); builder.Services.AddRazorComponents() .AddInteractiveServerComponents(); builder.Services.AddHttpContextAccessor(); var app = builder.Build(); // 配置HTTP请求管道 if (app.Environment.IsDevelopment()) { app.UseWebAssemblyDebugging(); } else { app.UseExceptionHandler("/Error", createScopeForErrors: true); // 默认HSTS值为30天,生产场景可按需修改,参考https://aka.ms/aspnetcore-hsts app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseAntiforgery(); app.UseAuthentication(); app.UseAuthorization(); app.MapRazorComponents<App>() .AddInteractiveServerRenderMode() .AddInteractiveWebAssemblyRenderMode() .AddAdditionalAssemblies(typeof(CertificateAuth.Client._Imports).Assembly); app.Run();
部署环境appsettings.json
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "AzureAd": { "Instance": "https://login.microsoftonline.com/", "Domain": "xxxx.onmicrosoft.com", "TenantId": "730237e0-xxxx-xxxx-xxxx-ccb0e9661c1e", "ClientId": "df903d59-xxxx-xxxx-xxxx-b55c1c3db538", "ClientCertificates": [ { "SourceType": "KeyVault", "KeyVaultUrl": "https://kvxxxxx.vault.azure.net/", "CertificateName": "certificateauthsample" } ], "ValidateAuthority": true, "CallbackPath": "/signin-oidc" }, "MicrosoftGraph": { "BaseUrl": "https://graph.microsoft.com/v1.0", "Scopes": "User.Read.All" } }
Kudu日志报错信息
2024-08-30 11:33:54.484 +00:00 [错误] Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler: 处理消息时发生异常。
System.ArgumentException: IDW10109: 传递给配置的所有客户端证书已过期或无法加载。(参数 'clientCredentials')
在 Microsoft.Identity.Web.ConfidentialClientApplicationBuilderExtension.WithClientCredentialsAsync(ConfidentialClientApplicationBuilder builder, IEnumerable1 clientCredentials, ILogger logger, ICredentialsLoader credentialsLoader, CredentialSourceLoaderParameters credentialSourceLoaderParameters) 在 Microsoft.Identity.Web.TokenAcquisition.BuildConfidentialClientApplicationAsync(MergedOptions mergedOptions) 在 Microsoft.Identity.Web.TokenAcquisition.GetOrBuildConfidentialClientApplicationAsync(MergedOptions mergedOptions) 在 Microsoft.Identity.Web.TokenAcquisition.AddAccountToCacheFromAuthorizationCodeAsync(AuthCodeRedemptionParameters authCodeRedemptionParameters) 在 Microsoft.Identity.Web.TokenAcquisitionAspNetCore.AddAccountToCacheFromAuthorizationCodeAsync(AuthorizationCodeReceivedContext context, IEnumerable1 scopes, String authenticationScheme)
在 Microsoft.Identity.Web.MicrosoftIdentityWebAppAuthenticationBuilder.<>c__DisplayClass11_1.<b__1>d.MoveNext()
--- 来自之前位置的堆栈跟踪结束 ---
在 Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.RunAuthorizationCodeReceivedEventAsync(OpenIdConnectMessage authorizationResponse, ClaimsPrincipal user, AuthenticationProperties properties, JwtSecurityToken jwt)
在 Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.HandleRemoteAuthenticateAsync()2024-08-30 11:33:54.488 +00:00 [错误] Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware: 执行请求时发生未处理的异常。
Microsoft.AspNetCore.Authentication.AuthenticationFailureException: 处理远程登录时遇到错误。
---> System.ArgumentException: IDW10109: 传递给配置的所有客户端证书已过期或无法加载。(参数 'clientCredentials')
在 Microsoft.Identity.Web.ConfidentialClientApplicationBuilderExtension.WithClientCredentialsAsync(ConfidentialClientApplicationBuilder builder, IEnumerable1 clientCredentials, ILogger logger, ICredentialsLoader credentialsLoader, CredentialSourceLoaderParameters credentialSourceLoaderParameters) 在 Microsoft.Identity.Web.TokenAcquisition.BuildConfidentialClientApplicationAsync(MergedOptions mergedOptions) 在 Microsoft.Identity.Web.TokenAcquisition.GetOrBuildConfidentialClientApplicationAsync(MergedOptions mergedOptions) 在 Microsoft.Identity.Web.TokenAcquisition.AddAccountToCacheFromAuthorizationCodeAsync(AuthCodeRedemptionParameters authCodeRedemptionParameters) 在 Microsoft.Identity.Web.TokenAcquisitionAspNetCore.AddAccountToCacheFromAuthorizationCodeAsync(AuthorizationCodeReceivedContext context, IEnumerable1 scopes, String authenticationScheme)
在 Microsoft.Identity.Web.MicrosoftIdentityWebAppAuthenticationBuilder.<>c__DisplayClass11_1.<b__1>d.MoveNext()
--- 来自之前位置的堆栈跟踪结束 ---
在 Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.RunAuthorizationCodeReceivedEventAsync(OpenIdConnectMessage authorizationResponse, ClaimsPrincipal user, AuthenticationProperties properties, JwtSecurityToken jwt)
在 Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.HandleRemoteAuthenticateAsync()
--- 内部异常堆栈跟踪结束 ---
在 Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync()
在 Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
在 Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddlewareImpl.g__Awaited|10_0(ExceptionHandlerMiddlewareImpl middleware, HttpContext context, Task task)
排查解决方案
根据报错IDW10109,核心问题是无法从Key Vault加载证书或证书已过期,按以下步骤排查:
验证证书有效性
检查Key Vault中的certificateauthsample证书是否过期,确认证书状态为"已启用";同时确认证书包含私钥(导入时需选择"导入证书和私钥")。确认托管身份权限
确保Azure App Service的托管身份(系统分配/用户分配)在Key Vault访问策略中拥有以下权限:- 证书权限:
Get、List - 密钥权限:
Get、List(证书私钥以密钥形式存储,需此权限)
确认访问策略已绑定到正确的托管身份,权限范围覆盖目标证书。
- 证书权限:
检查网络与防火墙设置
如果Key Vault启用了防火墙,需允许App Service的出站IP访问,或开启"允许受信任的Microsoft服务访问此密钥保管库"选项;若使用VNet,确认未阻止App Service访问Key Vault。验证配置正确性
确认appsettings.json中的KeyVaultUrl和CertificateName与Key Vault中的实际值完全匹配(注意大小写和拼写);同时检查Entra ID应用注册中上传的公钥指纹,需与Key Vault中的证书一致。测试托管身份访问
使用Azure CLI测试托管身份能否获取证书:az webapp identity assign --name <应用名称> --resource-group <资源组名称> az keyvault certificate show --name certificateauthsample --vault-name kvxxxxx更新依赖包版本
确保项目中Microsoft.Identity.Web包为最新稳定版本,旧版本可能存在Key Vault证书加载的兼容性问题。
内容的提问来源于stack exchange,提问作者Sivakumar G Nair

