Search code examples
authenticationexceptionblazor.net-8.0

Blazor AuthenticationStateProvider throw exception after NotifyAuthenticationStateChanged


I am getting following exception in browser logs.

    blazor.web.js:1 [2023-12-07T18:37:52.343Z] Error: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
   at System.Collections.Generic.List`1.Enumerator.MoveNext()
   at Microsoft.AspNetCore.Components.CascadingValueSource`1.<>c__DisplayClass10_0.<NotifyChangedAsync>b__0()
   at Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContextDispatcher.InvokeAsync(Action workItem)
   at Microsoft.AspNetCore.Components.CascadingValueSource`1.NotifyChangedAsync()
   at Microsoft.Extensions.DependencyInjection.CascadingAuthenticationStateServiceCollectionExtensions.AuthenticationStateCascadingValueSource.HandleAuthenticationStateChanged(Task`1 newAuthStateTask)
   at PortableMemory.UI.Services.Authentication.Implementations.AppAuthenticationStateProvider.AuthenticateUser(AuthenticationModel authModel) in D:\d\PortableMemory\PortableMemory.UI\PortableMemory.UI\Services\Authentication\Implementations\AppAuthenticationStateProvider.cs:line 38
   at PortableMemory.UI.Components.Login.LoginComponent.OnSubmit() in D:\d\PortableMemory\PortableMemory.UI\PortableMemory.UI\Components\Login\LoginComponent.razor.cs:line 34
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.Forms.EditForm.HandleSubmitAsync()
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)

My custom AuthenticationStateProvider implementation.

    public class AppAuthenticationStateProvider : AuthenticationStateProvider
{
    public override Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        var identity = new ClaimsIdentity();
        var user = new ClaimsPrincipal(identity);

        return Task.FromResult(new AuthenticationState(user));
    }


    public void AuthenticateUser(AuthenticationModel authModel)
    {
        var identity = new ClaimsIdentity(new[]
        {
        new Claim(ClaimTypes.Name, "bob"),
    }, "Custom Authentication");

        var user = new ClaimsPrincipal(identity);

        
        NotifyAuthenticationStateChanged(
            Task.FromResult(new AuthenticationState(user)));
    }
}

It occurs just after run application, so it is first call of this method from my side. Do you know why this error could appear ?

I am using .net8 and chrome.


Solution

  • I found the reason. If you component has AuthorizeView as well as the child component.