The Wayback Machine - https://web.archive.org/web/20211112074355/https://github.com/dotnet/aspnetcore/issues/28684
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
AFAde opened this issue Dec 16, 2020 · 22 comments

Comments

Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
@AFAde
Copy link

@AFAde AFAde commented Dec 16, 2020

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
@msftbot
Copy link
Contributor

@msftbot msftbot bot commented Dec 16, 2020

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.

Loading

@beausmyth1990
Copy link

@beausmyth1990 beausmyth1990 commented Dec 17, 2020

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?

Loading

@maxxhount
Copy link

@maxxhount maxxhount commented Dec 28, 2020

Im getting the same issue. Any update?

Loading

@shareonline
Copy link

@shareonline shareonline commented Jan 27, 2021

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

Loading

@vavdb
Copy link

@vavdb vavdb commented Feb 28, 2021

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

Loading

@cuperman007
Copy link

@cuperman007 cuperman007 commented Mar 5, 2021

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?

Loading

@FelipeCostaGualberto
Copy link

@FelipeCostaGualberto FelipeCostaGualberto commented Mar 19, 2021

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

Loading

@mikaelservin
Copy link

@mikaelservin mikaelservin commented Apr 16, 2021

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.

Loading

@ericjohnston
Copy link

@ericjohnston ericjohnston commented Apr 16, 2021

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.

Loading

@Panzerfury
Copy link

@Panzerfury Panzerfury commented Apr 17, 2021

I think this should be a priority.

Loading

@mikaelservin
Copy link

@mikaelservin mikaelservin commented Apr 19, 2021

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.

Loading

@beausmyth1990
Copy link

@beausmyth1990 beausmyth1990 commented Jun 1, 2021

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.

Loading

@shareonline
Copy link

@shareonline shareonline commented Jun 1, 2021

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.

Loading

@beausmyth1990
Copy link

@beausmyth1990 beausmyth1990 commented Jun 1, 2021

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

Loading

@shareonline
Copy link

@shareonline shareonline commented Jun 1, 2021

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

Loading

@AFAde
Copy link
Author

@AFAde AFAde commented Jun 1, 2021

@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

Loading

@agilenut
Copy link

@agilenut agilenut commented Jul 15, 2021

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?

Loading

@mkArtakMSFT mkArtakMSFT removed this from the Next sprint planning milestone Aug 10, 2021
@mkArtakMSFT mkArtakMSFT added this to the 6.0-rc2 milestone Aug 10, 2021
@mkArtakMSFT mkArtakMSFT added this to 6.0-rc2 (CC: 14 Sep) in ASP.NET Core Blazor & MVC 6.0 Aug 10, 2021
@javiercn javiercn self-assigned this Aug 26, 2021
@javiercn javiercn moved this from 6.0-rc2 (CC: 14 Sep) to In Progress in ASP.NET Core Blazor & MVC 6.0 Aug 31, 2021
@msftbot msftbot bot added the Working label Aug 31, 2021
@javiercn javiercn removed this from the 6.0-rc2 milestone Sep 8, 2021
@javiercn javiercn added this to the .NET 7 Planning milestone Sep 8, 2021
@javiercn javiercn moved this from In Progress to 6.0 in ASP.NET Core Blazor & MVC 6.0 Sep 8, 2021
@setezerocinco
Copy link

@setezerocinco setezerocinco commented Oct 6, 2021

Any news about this problem?

Loading

@mkArtakMSFT mkArtakMSFT removed this from 6.0 (CC: 18th Oct) in ASP.NET Core Blazor & MVC 6.0 Oct 13, 2021
@kfinke70
Copy link

@kfinke70 kfinke70 commented Oct 22, 2021

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

Loading

@Christoffleroux
Copy link

@Christoffleroux Christoffleroux commented Nov 10, 2021

Any new updated?

Loading

@mkArtakMSFT mkArtakMSFT removed this from the .NET 7 Planning milestone Nov 11, 2021
@mkArtakMSFT mkArtakMSFT added this to the Backlog milestone Nov 11, 2021
@msftbot
Copy link
Contributor

@msftbot msftbot bot commented Nov 11, 2021

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.

Loading

@MihaMarkic
Copy link
Contributor

@MihaMarkic MihaMarkic commented Nov 12, 2021

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?

Loading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment