@inject NavigationManager NavigationManager <CascadingAuthenticationState> <Router AppAssembly="@typeof(App).Assembly"> <Found Context="routeData"> <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)"> <NotAuthorized> @{ NavigationManager.NavigateTo("Login",true); } </NotAuthorized> </AuthorizeRouteView> <FocusOnNavigate RouteData="@routeData" Selector="h1"/> </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>
MainLayout.razor
@code{ [CascadingParameter] protected Task<AuthenticationState> AuthStat { get; set; } protected async override Task OnInitializedAsync() { base.OnInitialized(); var user = (await AuthStat).User; if(!user.Identity.IsAuthenticated) { NavigationManager.NavigateTo($"authentication/login?returnUrl={Uri.EscapeDataString(NavigationManager.Uri)}"); } } }
References
https://docs.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-5.0#customize-unauthorized-content-with-the-router-component
https://stackoverflow.com/questions/60840986/blazor-redirect-to-login-if-user-is-not-authenticated