HybridBlazor icon indicating copy to clipboard operation
HybridBlazor copied to clipboard

HttpContext with user is null

Open jareksgit opened this issue 3 years ago • 2 comments

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) }); }

jareksgit avatar Mar 30 '21 19:03 jareksgit

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?

изображение

jdtcn avatar Mar 31 '21 04:03 jdtcn

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?

jareksgit avatar Mar 31 '21 06:03 jareksgit