Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session Timeout redirect in Server side blazor

So it seems like Blazor does not currently support checking for an authentication timeout through inactivity using sliding expiration scheme.

what I am trying to achieve is to redirect user to login page once they had a session time. I can imagine that it has to be something in RevalidatingIdentityAuthenticationStateProvider where I need to detect activity on the site and redirect the user on the login page if the session has timeout but not sure how can I achieve this?

like image 674
Khan Avatar asked Sep 21 '26 03:09

Khan


1 Answers

you don't actually need to use

RevalidatingIdentityAuthenticationStateProvider

your app.razor just needs to look like this code:

<CascadingAuthenticationState> 
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" 
                     DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    **<RedirectToLogin> </RedirectToLogin>**
                </NotAuthorized>
                <Authorizing>
                    <h1>Authentication in progress</h1>
                    <p>Only visible while authentication is in progress.</p>
                </Authorizing>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
           ....
        </NotFound>
    </Router>
</CascadingAuthenticationState>

make sure that RedirectToLogin component redirect the user OnAfterRender callback should looks something like this

 [CascadingParameter]
    private Task<AuthenticationState> AuthenticationStateTask { get; set; }

    protected override async Task OnAfterRenderAsync(bool firstRender)
      {
        var authenticationState = await AuthenticationStateTask;
        try
        {
            if (authenticationState?.User?.Identity is null || !authenticationState.User.Identity.IsAuthenticated)
                {
                    var returnUrl = Navigation.ToBaseRelativePath(Navigation.Uri);

                    if (string.IsNullOrWhiteSpace(returnUrl))
                        Navigation.NavigateTo("/Identity/Account/Login", true);
                    else
                        Navigation.NavigateTo($"/Identity/Account/Login?returnUrl=~/{returnUrl}", true);
                }
        }
        catch (Exception e)
        {

            
        }
       
    }
like image 192
Nour Avatar answered Sep 23 '26 22:09

Nour