aspnetcore: Exception 'GetAuthenticationStateAsync was called before SetAuthenticationState.' thrown when calling AuthenticationStateProvider.GetAuthenticationStateAsync() method

Describe the bug

In my Blazor Server app, exactly as described in this bug report,

‘GetAuthenticationStateAsync was called before SetAuthenticationState.’

the GetAuthenticationStateAsync works only if the AuthenticationStateProvider service is synchronously called from a Blazor page.

In any async call running in the background it fails with the mentioned error message.

To Reproduce

Here is a sample repo: BlazorAppWithAuthenticationError

Just start the application and click on Fetch Data, the exception will be thrown immediately at the line 23 of the AuthTokenHandler class. I am using the HttpClient Factory pattern, which seems to lead to the issue.

Exceptions (if any)

System.InvalidOperationException: GetAuthenticationStateAsync was called before SetAuthenticationState.
   at Microsoft.AspNetCore.Components.Server.ServerAuthenticationStateProvider.GetAuthenticationStateAsync()
   at MyClasss.ExecuteAsync
...

Further technical details

  • ASP.NET Core version 5
  • output of dotnet --info .NET SDK (reflecting any global.json): Version: 5.0.101 Commit: d05174dc5a

Runtime Environment: OS Name: Windows OS Version: 10.0.18363 OS Platform: Windows RID: win10-x64 Base Path: C:\Program Files\dotnet\sdk\5.0.101\

Host (useful for support): Version: 5.0.1 Commit: b02e13abab

.NET SDKs installed: 3.0.100 [C:\Program Files\dotnet\sdk] 3.1.100 [C:\Program Files\dotnet\sdk] 3.1.301 [C:\Program Files\dotnet\sdk] 5.0.101 [C:\Program Files\dotnet\sdk]

.NET runtimes installed: Microsoft.AspNetCore.All 2.1.21 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] Microsoft.AspNetCore.All 2.1.23 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] Microsoft.AspNetCore.App 2.1.21 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 2.1.23 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 3.0.0 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 3.1.0 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 3.1.3 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 3.1.7 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 3.1.10 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 5.0.1 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.NETCore.App 2.1.21 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 2.1.23 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 3.0.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 3.1.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 3.1.3 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 3.1.7 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 3.1.8 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 3.1.10 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 5.0.1 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.WindowsDesktop.App 3.0.0 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 3.1.0 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 3.1.8 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 3.1.10 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 5.0.1 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]

  • Visual Studio 2019 16.8.3

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 6
  • Comments: 42 (10 by maintainers)

Most upvoted comments

This issue is still occurring when injecting AuthenticationStateProvider into a DelegatingHandler with latest .Net 5.

We really need a consistent way to get access to the user context. It is silly to have to do one thing when we are in Blazor land and another thing when we have a full HttpContext.

Status or workaround?

I think this should be a priority.

I can’t understand how this issue doesn’t have a bigger priority and how it wasn’t solved in a year. Even worse, tagging it as .NET 7 or Backlog. This isn’t an UI annoyance, it’s a bit more important don’t you think so?

Same… Blazor Server side on .NET 5. Trying to use in a userService together with EF Core and it is periodically failing

Thanks for contacting us. We’re moving this issue to the .NET 7 Planning milestone for future evaluation / consideration. Because it’s not immediately obvious that this is a bug in our framework, we would like to keep this around to collect more feedback, which can later help us determine the impact of it. We will re-evaluate this issue, during our next planning meeting(s). If we later determine, that the issue has no community involvement, or it’s very rare and low-impact issue, we will close it - so that the team can focus on more important and high impact issues. To learn more about what to expect next and how this issue will be handled you can read more about our triage process here.

Anu update here? Blazor Server should not be called “Production Ready” unless this is resolved! I can’t understand how this is not urgent? a few examples on why this is important:

  • User Context Service
  • Add User Context to EF dbcontext and apply global filter queries for multi-tenancy

Is there any fix for this? Having the same problem in a DelegatingHandler.

@shareonline I performed a quick test today by whipping-up a new Blazor Server-Side proj and injecting the AuthenticationStateProvider into a Scoped service. After calling the GetAuthenticationAsync method of the AutheticationStateProvider I did not get an exception. Could it be that this problem has been solved? Was the fix released in .Net 5? Who knows.

I am using .NET 5 (5.0.203) and definitely this issue has not been solved, I can still reproduce the error, please take a look at the repository which is mentioned in my first post

I’m having the same type of issue in a Blazor Server app when trying to use the information from a service by injecting AuthenticationStateProvider. The only workaround I’ve been able to work out is to use both IHttpContextAccessor and the AuthenticationStateProvider. It’s not recommended nor ideal, but it mostly works for my use case. I’m using the IHttpContextAccessor in middleware to set the properties I need on scoped objects that are injected into the service(s), but I’m using AuthenticationStateProvider in Blazor components, as recommended, where the HttpContext is already disposed. It definitely feels very hacky and I’m sure it could be done in a much more elegant way than my implementation, but it’s what works for now. I’m assuming this issue impacts anyone building a Blazor Server app that needs user state/context information outside of Blazor components.

I believe that it has been mentioned (somewhere in the Docs) that IHttpContextAccessor should NOT be used. Reason being - they might remove it in later versions, and not to mention that Server-Side only uses HTTP to initiate a web socket connection - it’s a completely different protocol of communication. Once the socket is open no more HTTP. I fear that this is not a viable workaround. We need this issue addressed - like, now.

THIS… Using the exact same method, and if not recommended or supported we truly need a fix as quick as possible… It needs to move a little faster with stuff like this in Blazor, if it is to become a mainstream framework. Don’t get me wrong development is fast for Blazor and I love it in general, but key issues like this hinders all “real” development that isn’t just front pages for companies.

I have been developing a Blazor Server application for a few weeks now and tried to add a UserService where I can get the signed in user’s identity and all post say you should use AuthenticationStateProvider injected to the service. I tried that but keep getting the error that I first should call SetAuthenticationState.

Is there really no work around for this? Is there any other way to get the identity or username for the signed in user that is possible to use in a service? The UserId is shown in the LoginDisplay component where @context.User.Identity.Name! is used.

@mkArtakMSFT This issue needs to stop being bumped. 5-6, 6-7, 7 to now 8.

What is a recommended pattern to use for accessing the user context from a service given that we are told not to use IHttpContextAccessor and AuthenticationStateProvider is not reliably usable when injected using DI? Thanks.

@shareonline I performed a quick test today by whipping-up a new Blazor Server-Side proj and injecting the AuthenticationStateProvider into a Scoped service. After calling the GetAuthenticationAsync method of the AutheticationStateProvider I did not get an exception. Could it be that this problem has been solved? Was the fix released in .Net 5? Who knows.

Hmm yeah maybe… I have only run into the errors when using it with my scoped EF context. I have solved it by using a transient dbcontext and a scoped service for my userservice. The userservice lives in my frontend project, where my dbcontext lives in my shared/service project. This works and so far so good.

Hi @javiercn , thanks a lot. By following your suggestions I was able to get the code working. If I get it right, when using pattern like the HttpClientFactory each control needs to inherit from CustomComponentBase, is this right?

One more: if I want to decouple pages/controls the from the core logic - for example, by following the MVVM architectural design pattern - what would be the best approach? In other words, is it possible to decouple the initialization and handling of the BlazorContextAccessor from the control? If yes, how? do you have any sample?

For those who are interested, you can take a look at the repository from the top of this thread, I just pushed the changes.

This is the handler; the rest is the same as in the sample in the docs.

public class ContextHandler : DelegatingHandler
{
    public ContextHandler(BlazorContextAccessor accessor)
   {
       _accessor = accessor;
   }

   protected Task SendAsync(HttpRequestMessage request)
   {
       var provider =_accessor.Services.GetRequiredService<AuthenticationStateProvider>();
       ...
   }
}

@MackinnonBuck do you have your sample with HttpClient around?

This is currently documented here