我有一个托管的Blazor WebAssembly应用程序,我强迫用户在启动时登录。我把这个逻辑放在MainLayout.razor页面上,如下所示:
protected override async Task OnInitializedAsync()
{
var user = (await AuthenticationStateTask).User;
if (user.Identity.IsAuthenticated)
{
await SetUserInfo(user);
}
else
{
AuthMessage = "User is NOT authenticated";
NavigationManager.NavigateTo($"authentication/login?returnUrl={Uri.EscapeDataString(NavigationManager.Uri)}");
}
}
我想做的是在用户成功登录后调用SetUserInfo方法(此时它在启动应用程序时总是导航到登录页面(,但不知道如何执行。除非手动刷新页面,否则OnInitializedAsync方法似乎只运行一次。有什么想法吗?提前谢谢。
想明白了。需要在组件中使用OnParametersSetAsync((。
[CascadingParameter] protected Task<AuthenticationState> AuthenticationStateTask { get; set; }
protected override async Task OnParametersSetAsync()
{
var user = (await AuthenticationStateTask).User;
if (user.Identity.IsAuthenticated)
{
await SetUserInfo(user);
}
}
使用OnAfterRenderAsync
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
var authenticationState = await authenticationStateTask;
if (authenticationState.User.Identity.IsAuthenticated)
{
}
}
}
关于LogiDisplay组件
@code {
[CascadingParameter]
private Task<AuthenticationState> authenticationStateTask { get; set; }
private string _authMessage;
private async Task LogUsername()
{
var authState = await authenticationStateTask;
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
_authMessage = $"{user.Identity.Name} is authenticated.";
wait SetUserInfo(user);
}
}
}
我认为最干净的解决方案是:
添加Blazor组分;呼叫我";(简称代码(
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@inject IDataService DataService
...
@code{
[CascadingParameter] protected Task<AuthenticationState> AuthState { get; set; } = null!;
protected override async Task OnInitializedAsync()
{
var user = (await AuthState).User;
if (user.Identity.IsAuthenticated)
{
var email = user.FindFirst("preferred_username").Value;
var user = await DataService.GetUserAsync(email);
}
}
}
并在LogiDiskplay.razor中"调用"它->授权上下文。
<AuthorizeView>
<Authorized>
@context.User.Identity?.Name!
<CallMe></CallMe>
<button class="nav-link btn btn-link" @onclick="BeginLogout">Log out</button>
</Authorized>
<NotAuthorized>
<a href="authentication/login">Log in</a>
</NotAuthorized>
</AuthorizeView>