按照文档,我创建了自定义 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.IsAuthentication为假。与文档中一样,以下内容将导致经过身份验证的用户:
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 和自定义身份验证状态提供程序的客户端 Blazor 身份验证
好吧,在我找到的.net核心源代码中
public virtual bool IsAuthenticated
{
get { return !string.IsNullOrEmpty(_authenticationType); }
}
这意味着我应该像下面这样更改我的代码:
private static AuthenticationState anonymousState =
new AuthenticationState(new ClaimsPrincipal(
new ClaimsIdentity(new Claim[] {}, "")));
// Or, can be even shorter like below
// private static AuthenticationState anonymousState =
// new AuthenticationState(new ClaimsPrincipal());
这会阻止我的 Blazor 应用正确显示,但我想这是一个不同的问题。