Blazor WebAssembly认证问题:无法完成授权访问
问题:Blazor WebAssembly授权失败,无法访问受保护页面
我开发了一个具备授权功能的基础Blazor WebAssembly应用,使用[AllowAnonymous]和[Authorize]特性管控路由访问权限,但始终无法完成授权以打开受保护页面。重定向后显示如下错误信息:
[Microsoft.AspNetCore.Authorization.DefaultAuthorizationService] Authorization failed. These requirements were not met: DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
页面路由相关代码
<CascadingAuthenticationState> <Router AppAssembly="@typeof(App).Assembly"> <Found Context="routeData"> <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)"> <NotAuthorized> @if (context.User.Identity is { IsAuthenticated: true }) { <text>You are not authorized to access this resource.</text> } else { <LoginRedirect/> } </NotAuthorized> <Authorizing> <text>Please wait, we are authorizing you ...</text> </Authorizing> </AuthorizeRouteView> <FocusOnNavigate RouteData="@routeData" Selector="h1"/> </Found> <NotFound> <PageTitle>Not found</PageTitle> <LayoutView Layout="@typeof(MainLayout)"> <p role="alert">Sorry, there's nothing at this address.</p> </LayoutView> </NotFound> </Router> </CascadingAuthenticationState>
认证状态获取代码
public override Task<AuthenticationState> GetAuthenticationStateAsync() { var identity = new ClaimsIdentity(); // ReSharper disable once InvertIf if (IsLoggedIn()) { var claims = new[] { new Claim(ClaimTypes.Name, _state.UserInfo!.Name), new Claim(ClaimTypes.NameIdentifier, _state.UserInfo!.Name) }; identity = new ClaimsIdentity(claims, "auth"); } return Task.FromResult(new AuthenticationState(new ClaimsPrincipal(identity))); }
排查与解决建议
- 验证
IsLoggedIn()方法逻辑:确认用户登录后该方法是否正确返回true,可通过日志或断点检查登录状态判断是否准确。 - 检查
_state.UserInfo赋值:确保登录后UserInfo已正确初始化,Name属性不为空,避免因空引用导致认证信息未正确生成。 - 确认认证状态提供器注册:在
Program.cs中检查是否已注册自定义的AuthenticationStateProvider,如builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthStateProvider>();,未注册则会使用默认提供器导致未认证状态。 - 触发认证状态变更:登录成功后需调用
NotifyAuthenticationStateChanged()方法,通知Blazor组件更新认证状态,否则页面会沿用旧的未认证信息。
内容的提问来源于stack exchange,提问作者Node.JS
相关产品推荐
相关产品推荐

