能否将Azure Active Directory身份验证接入现有Blazor Server项目?
已有Blazor Server应用接入Azure AD身份验证方案
完全可以手动添加身份验证能力,无需使用CLI新建项目,按以下步骤操作即可:
步骤1:安装依赖NuGet包
打开项目所在目录的终端,执行以下命令安装官方认证组件:
dotnet add package Microsoft.Identity.Web dotnet add package Microsoft.Identity.Web.UI
步骤2:配置身份验证参数
在appsettings.json中添加Azure AD配置节点,填入你在App Registration中获取的对应参数:
{ "AzureAd": { "Instance": "https://login.microsoftonline.com/", "TenantId": "你的租户ID", "ClientId": "你的应用注册客户端ID", "ClientSecret": "你的客户端密钥(如有配置)", "CallbackPath": "/signin-oidc" } }
步骤3:修改服务注册与中间件配置
编辑项目的Program.cs文件,按以下顺序添加身份验证相关配置:
// 服务注册部分,在var app = builder.Build()之前添加 builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd")); builder.Services.AddRazorPages() .AddMicrosoftIdentityUI(); builder.Services.AddAuthorizationCore(); // 中间件部分,在app.UseRouting()之后、app.MapBlazorHub()之前添加 app.UseAuthentication(); app.UseAuthorization(); // 端点映射部分,添加Razor Pages路由映射 app.MapRazorPages(); app.MapBlazorHub(); app.MapFallbackToPage("/_Host");
注意:必须严格保证UseAuthentication在UseAuthorization之前,顺序错误会导致身份验证失效
步骤4:修改根组件启用认证状态传递
编辑App.razor文件,用<CascadingAuthenticationState>包裹原有内容,同时将默认RouteView替换为AuthorizeRouteView:
<CascadingAuthenticationState> <Router AppAssembly="@typeof(App).Assembly"> <Found Context="routeData"> <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)"> <NotAuthorized> <p>你暂无权限访问该页面,请先登录。</p> </NotAuthorized> </AuthorizeRouteView> </Found> <NotFound> <PageTitle>未找到页面</PageTitle> <LayoutView Layout="@typeof(MainLayout)"> <p>抱歉,你访问的页面不存在。</p> </LayoutView> </NotFound> </Router> </CascadingAuthenticationState>
步骤5:添加登录/注销交互组件
在Shared目录下新建LoginDisplay.razor组件,用于展示登录状态和操作按钮:
<AuthorizeView> <Authorized> <span>您好,@context.User.Identity?.Name</span> <a href="MicrosoftIdentity/Account/SignOut">注销</a> </Authorized> <NotAuthorized> <a href="MicrosoftIdentity/Account/SignIn">登录</a> </NotAuthorized> </AuthorizeView>
将该组件添加到MainLayout.razor的导航栏区域,即可在全站展示登录入口。
额外核对项
请确认你此前的App Registration配置符合以下要求:
- 重定向URI已添加你现有项目的访问地址加后缀
/signin-oidc,比如https://localhost:5001/signin-oidc - 注销重定向URI已配置为你项目的访问地址加后缀
/signout-callback-oidc - 身份验证设置中已勾选「ID令牌(用于隐式流和混合流)」选项
配置完成后启动项目即可正常使用Azure AD身份验证能力。
内容的提问来源于stack exchange,提问作者privatename
相关产品推荐
相关产品推荐

