Live Chat Icon For mobile
Live Chat Icon

How do I redirect users to the login page when a session has timed out in Blazor?

Platform: Blazor| Category: General

To redirect users to your login page when their session has expired, create a RedirectLogin Razor component and implement the AuthenticationState to check whether sessions are expired or valid.
Follow these steps to redirect to a login page when sessions time out in Blazor:

Create a RedirectLogin component to redirect users to a login page when their session has expired.
@inject NavigationManager UriHelper
@code {
    public Task<AuthenticationState> StateAuthenticate { get; set; }
    protected override async Task OnInitializedAsync()
        var authenticationState = await StateAuthenticate;
        if (authenticationState?.User?.Identity is null || !authenticationState.User.Identity.IsAuthenticated)
            var returnUri = UriHelper.ToBaseRelativePath(UriHelper.Uri);
            if (string.IsNullOrWhiteSpace(returnUri))
                UriHelper.NavigateTo("YourLoginPath", true);
                UriHelper.NavigateTo($"YourLoginPath?returnUrl={returnUri}", true);

Now, initialize the RedirectLogin component in App.razor to identify whether a session is expired or valid.
<Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                    <RedirectLogin />
                // . . .
        // . . .

View Sample in GitHub

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.