I’m learning how authentication works in Blazor by playing around with a minimal implementation. I started with the Server template with auth “None” and the familiar Counter and Weather sample pages. I added a dummy AuthenticationStateProvider
as shown below and changed the RouteView
in Routes.razor
to an AuthorizeRouteView
without any additional configuration. I suspect this is where something else is required for the issue I’m having, maybe something to do with the special significance of the "/"
route.
AuthorizeView
works as expected on the Home, Counter, and Weather pages. @attribute [Authorize]
also works as expected on the Counter and Weather pages, but not on the Home page. If I use it on the Home page, I get this error:
InvalidOperationException: Unable to find the required ‘IAuthenticationService’ service. Please add all the required services by calling ‘IServiceCollection.AddAuthentication’ in the application startup code.
With AddAuthentication()
, the error changes:
InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action configureOptions).
With dummy scheme names, this error remains the same.
Why does [Authorize]
only behave this way on the Home page? What do I need to add to make it work there?
public class DummyAuthStateProvider : AuthenticationStateProvider
{
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
return Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new DummyIdentity())));
}
private class DummyIdentity : IIdentity
{
public string? AuthenticationType => "dummy";
public bool IsAuthenticated => true;
public string? Name => "dummy";
}
}
builder.Services.AddScoped<AuthenticationStateProvider, DummyAuthStateProvider>();