首页 > 解决方案 > 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));
}

我在这里想念什么?

标签: asp.net-coreblazorblazor-client-sideasp.net-core-security

解决方案


是的,只需使用:

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 身份验证


推荐阅读