Blazor United交互式Server应用集成MS Entra认证问题求助
纯Blazor United(仅Server渲染)集成MS Entra身份认证的正确方案
一、基础依赖与配置准备
- 安装必要NuGet包:
Microsoft.Identity.Web和Microsoft.Identity.Web.UI,后者负责生成登录/登出的路由端点。 - 在
appsettings.json中配置Azure AD参数:
"AzureAd": { "Instance": "https://login.microsoftonline.com/", "Domain": "你的租户域名", "TenantId": "你的租户ID", "ClientId": "你的应用客户端ID", "CallbackPath": "/signin-oidc", "SignedOutCallbackPath ": "/signout-callback-oidc" }
二、Program.cs核心配置(关键解决路由404与认证类型问题)
var builder = WebApplication.CreateBuilder(args); // 配置Blazor组件服务,指定仅启用交互式Server渲染 builder.Services.AddRazorComponents() .AddInteractiveServerComponents(); // 配置MS Entra认证服务,指定默认认证Scheme builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd")); // 添加授权策略,设置默认 fallback 策略确保未认证用户无法访问受保护资源 builder.Services.AddAuthorization(options => { options.FallbackPolicy = options.DefaultPolicy; }); // 添加Microsoft Identity UI控制器服务,这是生成/MicrosoftIdentity路由的核心 builder.Services.AddControllersWithViews() .AddMicrosoftIdentityUI(); var app = builder.Build(); // 中间件配置顺序不可颠倒 if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); // 启用认证与授权中间件,确保认证信息被正确注入 app.UseAuthentication(); app.UseAuthorization(); // 映射Blazor组件端点 app.MapRazorComponents<App>() .AddInteractiveServerRenderMode(); // 映射Identity UI的控制器路由,缺失会导致登录/登出路由404 app.MapControllers(); app.Run();
三、组件中实现登录/登出交互
直接使用Blazor的AuthorizeView组件结合Identity UI的路由:
<AuthorizeView> <Authorized> <p>当前登录用户:@context.User.Identity.Name</p> <a href="/MicrosoftIdentity/Account/SignOut">登出</a> </Authorized> <NotAuthorized> <a href="/MicrosoftIdentity/Account/SignIn">登录</a> </NotAuthorized> </AuthorizeView>
关键说明
- 无需自定义
ClaimsTransformer:认证类型为null的问题源于未正确配置默认认证Scheme及中间件顺序,上述配置会自动将ClaimsPrincipal.Identity.AuthenticationType设置为OpenIdConnectDefaults.AuthenticationScheme,确保AuthorizedView和[Authorize]属性正常工作。 - 全程无需引入WebAssembly组件:所有渲染逻辑基于Blazor Server模式,符合瘦客户端架构需求。
- 必须保留
AddControllersWithViews().AddMicrosoftIdentityUI()和app.MapControllers():这两个配置是生成/MicrosoftIdentity/Account/SignIn等路由的必要条件,缺失会导致404错误。
内容的提问来源于stack exchange,提问作者codeputer
相关产品推荐
相关产品推荐

