Session Timeout redirect in Server side blazor

Viewed 4791

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?

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)
        {

            
        }
       
    }
Related