Search code examples
.net-coreblazorblazor-webassembly

Custom `AuthenticationStateProvider` Authentication Failing


I have created a custom ApiAuthenticationStateProvider that after returning an AuthenticationState is still stating

info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed.

Here is a simplified version of my ApiAuthenticationStateProvider that is failing:

public class ApiAuthenticationStateProvider : AuthenticationStateProvider
{
   public override Task<AuthenticationState> GetAuthenticationStateAsync()
   {
       Console.WriteLine("Getting auth state...");
               
       var claims = new[] { new Claim(ClaimTypes.Name, "[email protected]") };
       var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(claims));
       var authState = Task.FromResult(new AuthenticationState(authenticatedUser));

       return Task.FromResult(authState);
   }
}

I can tell from the Console.WriteLine that is using my custom provider but to provide full details, here is the code i used to add that in Program.cs:

builder.Services.AddScoped<AuthenticationStateProvider, ApiAuthenticationStateProvider>();


Solution

  • The issue can be resolved in this answer. https://stackoverflow.com/a/20254797/2682662

    Basically when constructing the ClaimsIdentity you need to provide a string value for the authentication type.

    var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(claims, "Needs Auth Type Here"));