Search code examples
blazor-webassemblyasp.net-blazorasp.net-authentication

blazor AuthenticationStateProvider set as not logged in


I am trying to follow client-side blazers authentication and have a basic setup. I don't find any sample code explaining how to specify that the current user is not logged in. I have been trying to do this in the authentication state provider:

public class AuthProvider : AuthenticationStateProvider
{
    public override Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        // verify if the user is logged in.
        // if not:
        return Task.FromResult(null);
    }
}

I have also tried using Task.FromResult(new AuthenticationState(null)). Both simply throw null pointer functions. On the server it is as simple as calling a Fail() function. However, I don't see a AuthenticationState.Fail() function.


Solution

  • Try something like this:

    public static ClaimsPrincipal Anonymous
        => new ClaimsPrincipal(new ClaimsIdentity(Array.Empty<Claim>(), string.Empty));
    
    public override Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        // if not logged in
        return Task.FromResult(new AuthenticationState(Anonymous));
    }
    

    I think it's setting the AuthenticationType to a blank entry. I can't get to my code at the moment to assert it.