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:

  1. 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);

  2. 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 />
                    // . . .
            // . . .

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

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

Please submit your question and answer.