在blazor中未登录时将用户重定向到登录页面



我正试图修改与visual studio创建的stock blazor服务器项目,以便它将用户重定向到登录屏幕,如果他们没有登录。

MSDN上的文档到目前为止还不清楚如何做到这一点,我设法找到了一个so后Blazor重定向登录,如果用户没有经过身份验证,似乎可能会有所帮助,但专注于web组装,而不是Blazor服务器。

如何在blazor服务器中自动重定向一个人到登录屏幕?

我目前正在使用以下内容:

  1. 我在VS 2022中创建了一个blazor服务器应用程序,然后为登录屏幕创建了一个脚手架项目,指定ApplicationDbContext.cs作为上下文控制器。
  2. 1@attribute [Authorize]加入_imports.razor,@attribute [AllowAnonymous]加入Login.cshtml
  3. 根据Blazor重定向登录,如果用户没有经过身份验证,我创建了一个LoginRedirect.razor页面,其中包含以下内容:
@attribute [AllowAnonymous]
@inject NavigationManager _navigationManager
@code {
protected override void OnInitialized()
{
_navigationManager.NavigateTo("/Identity/Account/Login");
}
}
  1. 然后设置我的App.razor如下:
@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>

当我运行这个项目时,我得到一个导航异常,我似乎无法修复它。

可以使用AuthenticationStateProvider.GetAuthenticationStateAsync()方法获取当前用户的认证状态。

试试这个代码:

@using System.Security.Claims
@inject AuthenticationStateProvider _authenticationStateProvider
@inject NavigationManager _navigationManager;
@code {  
protected override async Task OnInitializedAsync()
{
var authState = await _authenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (!user.Identity.IsAuthenticated)
{
_navigationManager.NavigateTo("/Identity/Account/Login", false);
}
}
}

在上面的代码中,AuthenticationStateProvider.GetAuthenticationStateAsync()获取当前用户的身份验证状态。然后,如果他/她的身份验证状态未经过身份验证,它将重定向用户。

我使用了我在上面的问题中链接的帖子的一个答案,并设法通过在重定向页面中使用OnAfterRender而不是OnInitialized来获得重定向工作。

这是新的LoginRedirect.razor

@using System.Security.Claims
@inject AuthenticationStateProvider _authenticationStateProvider
@inject NavigationManager _navigationManager;
@code {
protected override void OnAfterRender(bool firstRender)
{
base.OnAfterRender(firstRender);
_navigationManager.NavigateTo("/login", false);
}
}

最新更新