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.
[RedirectLogin.razor]
@inject NavigationManager UriHelper
@code {
[CascadingParameter]
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);
}
else
{
UriHelper.NavigateTo($"YourLoginPath?returnUrl={returnUri}", true);
}
}
}
}
Now, initialize the RedirectLogin component in App.razor to identify whether a session is expired or valid.
[App.razor]
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
<RedirectLogin />
</NotAuthorized>
// . . .
</AuthorizeRouteView>
</Found>
// . . .
</Router>
Share with