aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

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

Open AFAde opened this issue 4 years ago • 31 comments

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

AFAde avatar Dec 16 '20 07:12 AFAde

Thanks for contacting us. We're moving this issue to the Next sprint planning milestone for future evaluation / consideration. We will evaluate the request when we are planning the work for the next milestone. To learn more about what to expect next and how this issue will be handled you can read more about our triage process here.

ghost avatar Dec 16 '20 17:12 ghost

I am also getting this issue and I cannot, for the life of me, figure out why. If I inject AuthenticationStateProvider via construction injection into any service and make a call to GetAuthenticationStateAsync() at any point in my code it will throw the exception mentioned by @AFAde. This will even occur when the user is logged-in, so I know that an the AuthenticationState must exist. Any thoughts on what the problem could be?

beausmyth1990 avatar Dec 17 '20 07:12 beausmyth1990

Im getting the same issue. Any update?

maxxhount avatar Dec 28 '20 15:12 maxxhount

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

shareonline avatar Jan 27 '21 09:01 shareonline

I ran into the same issue to get a token. I had to replace it with this to get it working:

        private readonly MicrosoftIdentityConsentAndConditionalAccessHandler _consentHandler;
        private readonly ITokenAcquisition _tokenAcquisition;

...

            var authUser = _consentHandler.User;
            var accessToken = await _tokenAcquisition
                .GetAccessTokenForUserAsync(_scopes, user: authUser)
                .ConfigureAwait(false);

Not sure if I am going to run into any issues.

The issue only seems to occur when I run it in a DelegatingHandler, I can access it fine in the actual HttpClient implementation

vavdb avatar Feb 28 '21 19:02 vavdb

I'm hitting same issue. I am using Azure AD for my logins. I have a generic repository pattern where I want to automatically add the current user name to a LastEditedBy field on all records when they are saved.

When injecting AuthenticationStateProvider into the service class, I get the error when calling the GetAuthenticationStateAsync method.

Many resources suggest using IHttpContextAccessor, but this does not work with Azure app service and we are advised not to use here

Is there another suitable work around to access the current user name in a service?

cuperman007 avatar Mar 05 '21 10:03 cuperman007

I'm also having this problem, I can't inject AuthenticationStateProvider in my services. Blazor Server Side with ASP.NET 5.

FelipeCostaGualberto avatar Mar 19 '21 03:03 FelipeCostaGualberto

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.

mikaelservin avatar Apr 16 '21 10:04 mikaelservin

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.

ericjohnston avatar Apr 16 '21 15:04 ericjohnston

I think this should be a priority.

Panzerfury avatar Apr 17 '21 22:04 Panzerfury

Thanks @ericjohnston for the reply. I will try and do something with IHttpContextAccessor even though I understand that it's not recommended. I am new to Blazor and .Net 5 and I am learning the hard way that things don't always work the way I think they should. I spent a couple of hours on this before I found this issue and understood that it was a bug and not something I was doing wrong again.

I hope there is a fix on the way for this and I think someone should write an official work around in the documentation so that people don't have to invent their own solutions.

mikaelservin avatar Apr 19 '21 06:04 mikaelservin

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.

beausmyth1990 avatar Jun 01 '21 02:06 beausmyth1990

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.

shareonline avatar Jun 01 '21 06:06 shareonline

@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.

beausmyth1990 avatar Jun 01 '21 06:06 beausmyth1990

@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.

shareonline avatar Jun 01 '21 06:06 shareonline

@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

AFAde avatar Jun 01 '21 06:06 AFAde

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?

agilenut avatar Jul 15 '21 02:07 agilenut

Any news about this problem?

fernandoweiler avatar Oct 06 '21 14:10 fernandoweiler

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

kfinke70 avatar Oct 22 '21 15:10 kfinke70

Any new updated?

Christoffleroux avatar Nov 10 '21 11:11 Christoffleroux

We've moved this issue to the Backlog milestone. This means that it is not going to be worked on for the coming release. We will reassess the backlog following the current release and consider this item at that time. To learn more about our issue management process and to have better expectation regarding different types of issues you can read our Triage Process.

ghost avatar Nov 11 '21 17:11 ghost

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?

MihaMarkic avatar Nov 12 '21 07:11 MihaMarkic

I thought this would get FIXED in dotnet 6.0!! this is Terrible!!

appsupport-gc avatar Jan 27 '22 21:01 appsupport-gc

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

aradhaghi avatar Apr 21 '22 20:04 aradhaghi

Does anyone have a solution/workaround for this?

JoeGER94 avatar May 19 '22 13:05 JoeGER94

I gave up waiting a solution for this and I'm just doing things hard way with JWT stored with local storage, etc. At least it works both for WASM an ServerSide.

FelipeCostaGualberto avatar May 19 '22 13:05 FelipeCostaGualberto

Thanks for your fast feedback. It's quite frustrating if you try to setup a multi-user-system. Maybe we can pray for @SteveSandersonMS to do something or even to give feedback to us

JoeGER94 avatar May 19 '22 13:05 JoeGER94

Does anyone have a solution/workaround for this?

Yes I created a process where I add in the access token to the HTTPClient every time I instantiate it using my own custom token provider class which depends upon AuthenticationStateProvider. I heard the issue has to do with HTTPClientFactory so perhaps avoiding that would work as well not sure. I can post my solution if helpful but it might be a few weeks.

appsupport-gc avatar May 19 '22 14:05 appsupport-gc

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.

ghost avatar May 24 '22 14:05 ghost

Having the same problem in DBContext

Gibrid89 avatar Jun 14 '22 11:06 Gibrid89