asp.net-core - AuthenticationStateProvider 的初始状态
问题描述
按照文档,我创建了我的自定义 AuthenticationStateProvider,如下所示:
public class ApiAuthStateProvider : AuthenticationStateProvider
{
private static AuthenticationState anonymousState = ?
private AuthenticationState _authState;
public ApiAuthStateProvider()
{
_authState = anonymousState;
}
public void SetAuthenticationState(AuthenticationState authState)
{
_authState = authState ?? anonymousState;
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
return Task.FromResult(_authState);
}
}
问题是如何初始化匿名状态,使 _authState.User.Identity.IsAuthenticated 为假。如文档中所示,以下内容将生成经过身份验证的用户:
private static AuthenticationState anonymousState =
new AuthenticationState(new ClaimsPrincipal(
new ClaimsIdentity(new Claim[] {}, "none")));
甚至以下导致经过身份验证的用户:
public class AnonymousIdentity : IIdentity
{
public string AuthenticationType => "none";
public bool IsAuthenticated => false;
public string Name => string.Empty;
}
private static AuthenticationState anonymousState;
static ApiAuthStateProvider()
{
var anonymousIdentity = new AnonymousIdentity();
var user = new ClaimsIdentity(anonymousIdentity);
anonymousState = new AuthenticationState(
new ClaimsPrincipal(user));
}
我在这里想念什么?
解决方案
是的,只需使用:
new AuthenticationState(new ClaimsPrincipal());
这段代码对我有用:
public class CustomAuthenticationProvider : AuthenticationStateProvider
{
private readonly HttpClient _httpClient;
public CustomAuthenticationProvider(HttpClient httpClient)
{
_httpClient = httpClient;
}
public override async Task<AuthenticationState>
GetAuthenticationStateAsync()
{
ClaimsPrincipal user;
// Call the GetUser method to get the status
// This only sets things like the AuthorizeView
// and the AuthenticationState CascadingParameter
var result =
await _httpClient.GetJsonAsync<BlazorUser>("api/user/GetUser");
// Was a UserName returned?
if (result.UserName != "")
{
// Create a ClaimsPrincipal for the user
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, result.UserName),
}, "AzureAdAuth");
user = new ClaimsPrincipal(identity);
}
else
{
user = new ClaimsPrincipal(); // Not logged in
}
return await Task.FromResult(new AuthenticationState(user));
}
}
请参阅:使用 Azure AD 和自定义 AuthenticationStateProvider 的客户端 Blazor 身份验证
推荐阅读
- node.js - 从 POST 反应中获取名字的正确语法
- javascript - Angular i18n 动态文本
- c# - 如何在 ASP.NET Core MVC 中从 .docs.microsoft.com 获取“.TokenAuthCookies”cookie?
- javascript - 在 javascript 中使用哈希表搜索对象值
- java - SpringBoot @Scheduled 每两次执行之间的随机延迟
- node.js - 在 dialogflow webhook 中设置了响应,但它返回未设置响应
- reactjs - react-bootstrap-typeahead labelKey 打字稿
- javascript - 不同句子的随机组合
- python - 计算抵押贷款 - python 3.8.3
- c# - 如何在 C# 中使用 Imap 过滤来自特定发件人的电子邮件?