Blazor Server同时集成Web App与Web API的AzureAD认证配置问题
场景说明
我的Blazor Server项目需要同时提供两类服务:
- Web API:供桌面客户端调用
- Web App:作为管理工具用于服务器配置管理
所有访问都通过AzureAD实现认证与授权,Razor页面使用@attribute [Authorize(Roles = "MyRole")],API控制器使用[Authorize(Roles = "MyRole")]特性。
AzureAD配置
"AzureAd": { "Instance": "https://login.microsoftonline.com/", "Domain": "[mydomain.com]", "TenantId": "[myTenantId]", "ClientId": "[myClientId]", "CallbackPath": "/signin-oidc", "SignedOutCallbackPath ": "/signout-callback-oidc" }
单独配置的正常状态
分别配置Web API或Web App时,认证授权均可正常工作:
Web API的Startup.cs配置
services.AddMicrosoftIdentityWebApiAuthentication(GetConfiguration()); services.AddControllersWithViews(); services.AddRazorPages(); services.AddServerSideBlazor();
Web App的Startup.cs配置
services.AddMicrosoftIdentityWebAppAuthentication(GetConfiguration()); services.AddControllersWithViews().AddMicrosoftIdentityUI(); services.AddRazorPages(); services.AddServerSideBlazor().AddMicrosoftIdentityConsentHandler();
当前问题与尝试的配置
官方文档支持同时启用Web App和Web API的场景,但我尝试的配置出现异常:
尝试的配置代码
var configuration = GetConfiguration(); services.AddMicrosoftIdentityWebApiAuthentication(configuration); services.AddMicrosoftIdentityWebAppAuthentication(configuration); services.AddControllersWithViews().AddMicrosoftIdentityUI(); services.AddRazorPages(); services.AddServerSideBlazor().AddMicrosoftIdentityConsentHandler();
异常现象
Web API的认证正常,但Web App在AzureAD登录成功跳转后,无用户登录状态。
解决思路建议
明确认证方案,避免冲突
默认情况下,AddMicrosoftIdentityWebApiAuthentication注册JwtBearer方案,AddMicrosoftIdentityWebAppAuthentication注册OpenIdConnect和Cookie方案。需确保Web App使用的Cookie认证为默认方案,或在Blazor、Razor页面中显式指定使用Cookie方案。显式配置默认认证方案
通过AddAuthentication统一指定默认方案,同时为API端点单独指定JwtBearer方案:services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddMicrosoftIdentityWebApp(configuration) .AddMicrosoftIdentityWebApi(configuration) .AddCookie();调整服务注册顺序
先注册Web App的认证服务,再注册Web API的认证服务,避免默认方案被后续注册覆盖:services.AddMicrosoftIdentityWebAppAuthentication(configuration); services.AddMicrosoftIdentityWebApiAuthentication(configuration);显式指定Blazor的认证方案
在配置Blazor服务时,明确指定使用Cookie认证方案:services.AddServerSideBlazor(options => { options.AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme; }).AddMicrosoftIdentityConsentHandler();验证Cookie状态
登录成功后检查浏览器的.AspNetCore.CookiesCookie,确认OIDC回调后是否正确写入了用户身份信息。
内容的提问来源于stack exchange,提问作者David Renz

