jdtcn / HybridBlazor

Simultaneous Blazor Hosting Models and switching at runtime
MIT License
97 stars 24 forks source link

HttpContext with user is null #4

Open jareksgit opened 3 years ago

jareksgit commented 3 years ago

Hey and thanks for the effort and the illustration. But the whole thing works a bit limited. When the application is initially loaded, the server-side httpContext with the user is empty, so an exception is thrown.

public Task<CurrentUser> CurrentUserInfo() { **var user = httpContextAccessor.HttpContext.User;** return Task.FromResult(new CurrentUser { IsAuthenticated = user.Identity.IsAuthenticated, UserName = user.Identity.Name, Claims = user.Claims .ToDictionary(c => c.Type, c => c.Value) }); }

jdtcn commented 3 years ago

Hi,

It's a strange situation because HttpContext.User must have non-null value regardless authentication state. Have you made any changes in the project files? What environment do you use? Is httpContextAccessor null or httpContextAccessor.HttpContext is null?

изображение

jareksgit commented 3 years ago

Hello,

in my local environment the whole thing ran without any problems and I can also reproduce your debugging result locally. After deploying it on Azure, I became aware of the problem. Except for the database and some settings, I made no changes and deployed it 1 to 1.

After my research, see Stackoverflow Answer 1 with a small link in it to Stackoverflow Answer 2. And there I found a link to the official documentation on this matter: Documentation Link And in it the note that the HttpContext isn't guaranteed to be available within the IHttpContextAccessor, nor is it guaranteed to be holding the context that started the Blazor app.

The Blazor Server Starter via Visual Studio does not visibly access the httpcontext to query the user, but uses a helper method (RevalidatingServerAuthenticationStateProvider) to get our current user state. Maybe this is an approach to bypass the whole thing with the HttpContext?