如何在Blazor与Azure B2C中实现除首页外的登录提示?
解决方案
步骤1:调整全局授权策略
修改Program.cs中的授权配置,移除全局强制认证的 fallback 策略,仅保留默认授权规则:
builder.Services.AddAuthorization(options => { // 移除该行:options.FallbackPolicy = options.DefaultPolicy; // 仅对标记[Authorize]的资源应用授权要求 });
步骤2:配置Blazor路由的授权检查
修改App.razor,使用AuthorizeRouteView处理内部路由的授权逻辑,未授权时触发登录跳转:
<Router AppAssembly="@typeof(App).Assembly"> <Found Context="routeData"> <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)"> <NotAuthorized> <RedirectToLogin /> </NotAuthorized> <Authorizing> <p>正在验证身份...</p> </Authorizing> </AuthorizeRouteView> </Found> <NotFound> <PageTitle>Not found</PageTitle> <LayoutView Layout="@typeof(MainLayout)"> <p>抱歉,未找到该页面。</p> </LayoutView> </NotFound> </Router>
步骤3:创建登录跳转组件
添加RedirectToLogin.razor组件,负责引导用户跳转到登录页面:
@inject NavigationManager NavigationManager @inject IAuthenticationService AuthenticationService @code { protected override async Task OnInitializedAsync() { var returnUrl = NavigationManager.ToBaseRelativePath(NavigationManager.Uri); await AuthenticationService.ChallengeAsync(new AuthenticationProperties { RedirectUri = returnUrl != string.Empty ? $"/{returnUrl}" : "/" }); } }
步骤4:设置页面授权属性
- 给首页
Index.razor添加匿名访问标记:[AllowAnonymous] public partial class Index { // 页面逻辑 } - 给其他所有需要登录的页面(如
Counter.razor、FetchData.razor)添加授权标记:[Authorize] public partial class Counter { // 页面逻辑 }
步骤5:保留_Host页面的匿名权限
确保Program.cs中保留对/_Host页面的匿名访问允许:
builder.Services.AddRazorPages(options => { options.Conventions.AllowAnonymousToPage("/_Host"); }) .AddMvcOptions(options => { }) .AddMicrosoftIdentityUI();
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

