访问Blazor服务器中的AuthenticationState以在单个位置更新组件
我是否可以在Blazor中使用某种方法来检查MainLayout.razor等位置的身份验证状态,以便在导航到组件时,如果令牌过期,我可以使状态无效?例如,如果使用OnAfterRenderAsync,则为时已晚,因为页面已呈现。我不想对每个组件重复检查。所以我想知道是否有类似于生命周期函数的东西,每次您导航到一个组件时都会调用它,我可以在其中执行类似的操作访问Blazor服务器中的AuthenticationState以在单个位置更新组件,blazor,blazor-server-side,Blazor,Blazor Server Side,我是否可以在Blazor中使用某种方法来检查MainLayout.razor等位置的身份验证状态,以便在导航到组件时,如果令牌过期,我可以使状态无效?例如,如果使用OnAfterRenderAsync,则为时已晚,因为页面已呈现。我不想对每个组件重复检查。所以我想知道是否有类似于生命周期函数的东西,每次您导航到一个组件时都会调用它,我可以在其中执行类似的操作 var authState = await AuthenticationStateProvider.GetAuthenticationSt
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
if (authState.User.Identity != null && authState.User.Identity.IsAuthenticated == false)
{
Logout();
}
StateHasChanged();
我为此使用作用域服务 在
Program.cs中
builder.Services.AddScoped<IIdentityBroker, IdentityBroker>();
public class IdentityBroker : IIdentityBroker
{
public IdentityBroker(AuthenticationStateProvider authenticationStateProvider)
{
this.authenticationStateProvider = authenticationStateProvider;
authenticationStateProvider.AuthenticationStateChanged += AuthenticationStateProvider_AuthenticationStateChanged;
}
public IdentityInformation IdentityInformation => this.identityInformation;
public event EventHandler AuthenticationStateChanged;
private void AuthenticationStateProvider_AuthenticationStateChanged(Task<AuthenticationState> task)
{
var authState = task.Result;
UpdateIdentityInfo(authState);
AuthenticationStateChanged?.Invoke(this, new EventArgs());
}
public async ValueTask<IdentityInformation> GetIdentityInfoAsync()
{
if (identityInformation == default)
{
var authState = await authenticationStateProvider.GetAuthenticationStateAsync();
UpdateIdentityInfo(authState);
}
return identityInformation;
}
private void UpdateIdentityInfo(AuthenticationState authState)
{
if (authState.User.Identity.IsAuthenticated)
{
var user = authState.User;
this.identityInformation = new IdentityInformation
{
DisplayName = user.Identity.Name,
Email = (user.FindFirst("email")?.Value ?? ""),
Oid = (user.FindFirst("oid")?.Value ?? "")
};
}
else
{
this.identityInformation = default;
}
}
private readonly AuthenticationStateProvider authenticationStateProvider;
private IdentityInformation identityInformation = default;
}
在主布局.razor的底部:
@code {
[Inject]
public IIdentityBroker IdentityBroker { get; set; }
protected override async Task OnInitializedAsync()
{
await IdentityBroker.GetIdentityInfoAsync();
await base.OnInitializedAsync();
}
}
我的问题是像OnInitializedAsync这样的生命周期方法只被调用一次,但我要寻找的是每次导航到组件时都会被调用的方法,这样我就可以检查authState,并且每次调用OnAfterRenderAsync时都只能在页面完成后调用rendered@user2857208这就是我订阅的原因
authenticationStateProvider.AuthenticationStateChanged+=authenticationStateProvider\u AuthenticationStateChanged
@attribute[Authorize]在您导航到的任何页面上都会检查身份验证状态。您能否详细说明事件是如何触发的?页面上的@attribute[Authorize]不会触发获取身份验证状态