I'm trying to modify the stock blazor server project that gets created with visual studio so that it redirects the user to the login screen if they're not logged in.
The documentation on MSDN hasn't been clear so far as for how to do that and I managed to find a SO post Blazor redirect to login if user is not authenticated that seemed like it may be helpful, but is focused on web assembly, and not blazor server.
How do I redirect a person to the login screen automatically in blazor server?
I'm currently using the following:
- I created a blazor server app in VS 2022, then created a scaffolded item for the login screen, assigning the
ApplicationDbContext.csas the context controller. - I Added
@attribute [Authorize]to_imports.razorand@attribute [AllowAnonymous]toLogin.cshtml - According to Blazor redirect to login if user is not authenticated I created a
LoginRedirect.razorpage that contains the following:
@attribute [AllowAnonymous]@inject NavigationManager _navigationManager@code { protected override void OnInitialized() { _navigationManager.NavigateTo("/Identity/Account/Login"); }}- Then I set up my
App.razoras follows:
@using LoginScaffolding.Pages@using Microsoft.AspNetCore.Authorization@using Microsoft.AspNetCore.Components.Authorization@using Microsoft.AspNetCore.Authentication<CascadingAuthenticationState><Router AppAssembly="@typeof(App).Assembly"><Found Context="routeData"><AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" /><FocusOnNavigate RouteData="@routeData" Selector="h1" /><NotAuthorized><LoginRedirect /></NotAuthorized></Found><NotFound><PageTitle>Not found</PageTitle><LayoutView Layout="@typeof(MainLayout)"><p role="alert">Sorry, there's nothing at this address.</p></LayoutView></NotFound></Router></CascadingAuthenticationState>When I run this project I get a navigation exception, and I can't seem to fix it.