In this particular case I am only interested in getting info whether the user is logged in or not.
Following the answers How to enable/disable elements depending whether the user is logged in or not? I can fetch this information but there is one odd problem.
I use Blazor demo app which displays provided "LoginDisplay.razor" component at top, my own page uses following code:
@code {
protected override async Task OnInitializedAsync()
{
Console.WriteLine("Init");
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var authenticated = authState.User.Identity?.IsAuthenticated ?? false;
Console.WriteLine($"We are {authenticated}");
}
}
I have three steps when using this app:
I start the app, I am not logged in, "LoginDisplay" shows "log in" prompt and my code prints I am not authenticated -- good
I click on "log in", I log in, I am redirected back to my page -- "LoginDisplay" now shows my name, yet my code still prints I am not authenticated (this incorrect printout happens when using "NavMenu.razor" but it is fine when when using "Index.razor" -- see update below)
I hit F5 (reload the page) -- "LoginDisplay" shows my name, and the code prints I am authenticated -- as expected
So step (2) is problematic -- I should get the info I am logged in (because I am), and obviously "LoginDisplay" is capable of realizing this fact. So what logic should I add to my code that it too would show I am logged in?
Update After @enet reply I realized the outcome of the step (2) depends where you put this code -- if it placed in "NavMenu.razor" right after logging in the printout states you are not authorized. When I put the same code in "Index.razor" (home page) the printout correctly states I am logged in.
I can see that rendering "NavMenu" is almost immediate, while "Index" is rendered after some pause. So the problem is more "how to get fresh authentication info regardless the page is used?".