Blazor-在未经身份验证的情况下打开主页时,永远不会重定向到登录页面



我将Blazor与.net 6一起使用。在app.razor页面中,我有AutorizedRouteViewNotAuthorized的默认值。除了主页外,一切都很好。如果没有任何身份验证,则应重定向到登录页面,但它始终检测到NotAuthorized页面。

App.razor

<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<Authorizing>
<text> Please wait, we are authorizing the user. </text>
</Authorizing>
<NotAuthorized>
<div class="text-center">
<img src="/assets/img/restrito.png" class="rounded" alt="não encontrado">
<br /><br>
<h1 class="fw-bolder">Não possui acesso a esta página.</h1>
</div>
</NotAuthorized>
</AuthorizeRouteView>
</Found>
<NotFound>
@{
<div class="text-center">
<img src="/assets/img/404.png" class="rounded" alt="não encontrado">
<br /><br>
<h1 class="fw-bolder">Página não encontrada.</h1>
<a href="">Retornar à página principal</a>
</div>
}
</NotFound>
</Router>
</CascadingAuthenticationState>

AppRouteView.cs

public class AppRouteView : RouteView
{
[Inject]
private NavigationManager _navigationManager { get; set; }
[Inject]
private IAccountService _accountService { get; set; }
protected override void Render(RenderTreeBuilder builder)
{
// var authorize = Attribute.GetCustomAttribute(RouteData.PageType, typeof(AuthorizeAttribute)) != null;
if (_accountService.User == null)
{
_navigationManager.NavigateTo("account/login");
}
else
{
base.Render(builder);
}
}
}

索引.razor

@page "/"
@using VidaConfortoApplication.Client.Services.Interfaces
@attribute [Authorize]
@inject IAccountService _accountService
<div class="p-4">
<div class="container">
<h1>Olá @_accountService.User?.Name!</h1>
<p>Está autenticado na aplicação GesSad!</p>
<p><NavLink href="users">Gerir utilizadores</NavLink></p>
</div>
</div>

登录剃刀页面没有任何[授权]属性

您需要在<NotAuthorized>标记中自己处理重定向到登录页面的操作。检查用户是否经过身份验证,如果没有,则将其重定向到登录页面。这里有一个例子:

<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
@if (!context.User.Identity.IsAuthenticated)
{
<RedirectToLogin />
}
else
{
<p>You are not authorized to access this resource.</p>
}
</NotAuthorized>
</AuthorizeRouteView>

请注意,这也处理了身份验证和授权之间的区别。用户可以登录到某个站点(经过身份验证(,而没有访问某些资源的权限(经过授权(。

<RedirectToLogin />组件中,只需在OnInitialized()OnInitializedAsync()中重定向用户。这里有一个简单的例子:

@inject NavigationManager _nav
@code {
protected override void OnInitialized()
{
_nav.NavigateTo("/account/login");
}
}

如果您希望用户返回到他们最初尝试输入的页面,请在重定向到登录之前获取目标uri,并将其作为查询参数传递到登录页面(以处理登录后的重定向(。然后,<RedirectToLogin />组件可能看起来像这样:

@inject NavigationManager _nav
@code {
protected override void OnInitialized()
{
var path = _nav.ToBaseRelativePath(_nav.Uri);
_nav.NavigateTo($"/account/login?returnUrl={path}");
}
}

相关内容

  • 没有找到相关文章

最新更新