如果您的Blazor WASM托管在.net .Server项目中(解决方案中有3个项目:.Client、.Server和.Shared),请将.RequireAuthorization添加到以下位置:
.Server/Program.cs(而不是.Client项目中的那一个)
app.MapFallbackToFile("index.html").RequireAuthorization();
// redirect to login page BEFORE loading Blazor WASM page if auth is missing,
// use when ALL Blazor pages require autentication
// and you don't handle login screens etc. in Blazor but in the backend
您可以将您的``标签包含在`app.razor`文件中,并添加自定义的`LoginRedirect`组件,建议由@ssamko提供,但请确保如果身份验证URL由.Server应用程序处理,则使用强制重定向。
app.razor:
@using Microsoft.AspNetCore.Components.Authorization
@using YourBlazor.Client.Components
<CascadingAuthenticationState>
<AuthorizeView>
<Authorized>
Current user: @context.User.Identity.Name
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
<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>
</Authorized>
<NotAuthorized>
<LoginRedirect />
</NotAuthorized>
</AuthorizeView>
组件/LoginRedirect.razor(注意forceLoad:true);
@using System.Web
@attribute [Microsoft.AspNetCore.Authorization.AllowAnonymous]
@inject NavigationManager _navigationManager
@code {
protected override void OnInitialized()
{
_navigationManager.NavigateTo("/authentication/login?returnUrl=" + HttpUtility.UrlEncode(_navigationManager.ToBaseRelativePath(_navigationManager.Uri)), forceLoad:true);
}
}