Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Blazor Server .NET 8: How to properly access ProtectedLocalStorage after login using NavigationManager.NavigateTo()

$
0
0

After successful login (JWT-based authentication stored in protectedLocalStorage), I want to redirect to ReturnUrl if exists.

When the ReturnUrl -destination page- has the Authorize attribute & GetAuthenticationStateAsync() is executed, protectedLocalStorage becomes null after NavigationManager.NavigateTo() is executed.

This is the relevant code for login page

await protectedLocalStorage.SetAsync("authToken", token);NavigationManager.NavigateTo(ReturnUrl ?? "");

And I'm trying to get protectedLocalStorage at GetAuthenticationStateAsync() like this

ProtectedBrowserStorageResult<string> result;try{    result = await protectedLocalStorage.GetAsync<string>("authToken"); //protectedLocalStorage is null after the redirect}catch{    result = new();}var anonymous = new ClaimsPrincipal(new ClaimsIdentity());if (!result.Success) //Since protectedLocalStorage is null I get redirected back to login page.{    return new AuthenticationState(anonymous);}

I disabled the prerender at App.razor& it's working fine except when trying to redirect to an authorized component

<Routes @rendermode="@RenderModeForPage"/>@code {     [CascadingParameter] private HttpContext HttpContext { get; set; } = default!;     private IComponentRenderMode? RenderModeForPage => HttpContext.Request.Path.StartsWithSegments("/Account/Login") ? null : new InteractiveServerRenderMode(prerender: false);     //I added this because when login page's render mode is interactive server, it keeps reloading indefinitely}

The login page keeps reloading as mentioned in the above comment due to this code in AccountLayout

protected override void OnParametersSet(){    if (HttpContext is null)    {        // If this code runs, we're currently rendering in interactive mode, so there is no HttpContext.        // The identity pages need to set cookies, so they require an HttpContext. To achieve this we        // must transition back from interactive mode to a server-rendered page.        NavigationManager.Refresh(forceReload: true);    }}

If I navigate to the authorized component normally by clicking on a link or typing the url -after login- it's working properly. This is only happening after using NavigationManager.NavigateTo() function.

It looks like the NavigateTo() function calls GetAuthenticationStateAsync() too early in the Blazor life cycle that the protectedLocalStorage is not ready yet.

I think the issue is due to login page render mode, so how to get the protectedLocalStorage properly?


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>