If someone is looking for a complete solution, this is how I did it.
Solution
Step 1:
Create a razor component named RedirectToLogin.razor
wherever you want.
For eg: I'm creating it inside Areas/Identity/Components
And add the following code to this file:
@inject NavigationManager Navigation
@code {
[Parameter]
public string ReturnUrl { get; set; }
protected override async Task OnInitializedAsync()
{
ReturnUrl = "~/" + ReturnUrl;
Navigation.NavigateTo("Identity/Account/Login?returnUrl=" + ReturnUrl, true);
await base.OnInitializedAsync();
}
}
Step 2:
Use this component from App.razor
inside <NotAuthorized></NotAuthorized>
:
@inject NavigationManager Navigation
@using HMT.Web.Server.Areas.Identity.Components
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
@if (!context.User.Identity.IsAuthenticated)
{
<RedirectToLogin ReturnUrl="@Navigation.ToBaseRelativePath(Navigation.Uri)" />
}
else
{
<p role="alert">Sorry, you're not authorized to view this page.</p>
}
</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>
Complete source code
https://github.com/akhanalcs/blazor-server-auth/tree/feature/LayoutWithIdentityPages
Demo
Start the app and try to get to an authorized view from the browser (Counter page here as an example):
You'll be redirected to Login page:
You'll log in successfully and get to the Counter page: