如何在C#中创建未认证匿名主体?适用于Blazor WASM的AuthenticationStateProvider
Blazor WebAssembly AuthenticationStateProvider 匿名主体处理
当从浏览器获取的用户信息(user)为null时,需返回未认证的匿名ClaimsPrincipal,以下是补充完整后的代码实现:
public override async Task<AuthenticationState> GetAuthenticationStateAsync() { var principal = new ClaimsPrincipal(); var user = await _userService.FetchUserFromBrowser(); if (user is not null) { var authenticatedUser = await _userService.SendAuthenticateRequestAsync(user.Username, user.Password); if (authenticatedUser is not null) { principal = authenticatedUser.ToClaimsPrincipal(); CurrentUser = authenticatedUser; } } else { // 显式初始化未认证的匿名主体 principal = new ClaimsPrincipal(new ClaimsIdentity()); } return new AuthenticationState(principal); }
说明
- 默认构造的
ClaimsPrincipal本身就代表未认证的匿名用户,其关联的ClaimsIdentity的IsAuthenticated属性为false。 - 显式创建
new ClaimsIdentity()并赋值给ClaimsPrincipal,能更清晰地表明这是一个匿名未认证主体,语义上更明确。
内容的提问来源于stack exchange,提问作者mz1378
相关产品推荐
相关产品推荐

