【发布时间】:2021-06-12 13:27:23
【问题描述】:
我有一个关于 Blazor 5.0 中角色管理的问题。
当用户已经通过身份验证时,我想添加或删除角色。在我的页面中,我经常使用
[CascadingParameter]
protected Task<AuthenticationState> AuthState { get; set; }
检查用户是否具有正确的角色。
有一次我使用此方法更新角色,但发生了意外行为:
protected async Task Cancel()
{
var User = await UM.GetUserAsync((await AuthState).User);
Console.WriteLine("---Before---");
var BoolAuth1 = (await AuthState).User.IsInRole(Utilisateur.Role_Abonne);
Console.WriteLine($"AuthState status for role : {BoolAuth1}");
var Bool1 =await UM.IsInRoleAsync(User, Utilisateur.Role_Abonne);
Console.WriteLine($"UserManager status for role : {Bool1}");
await UM.RemoveFromRoleAsync(User, Utilisateur.Role_Abonne);
Console.WriteLine("---After----");
var BoolAuth2 = (await AuthState).User.IsInRole(Utilisateur.Role_Abonne);
Console.WriteLine($"AuthState status for role : {BoolAuth2}");
var Bool2 = await UM.IsInRoleAsync(User, Utilisateur.Role_Abonne);
Console.WriteLine($"UserManager status for role : {Bool2}");
}
结果是:
---Before---
AuthState status for role : True
UserManager status for role : True
---After----
AuthState status for role : True
UserManager status for role : False
在数据库中进行了更改,但未刷新 AuthState,即使重新加载页面也无法解决问题。我必须注销,然后重新登录以刷新 AuthState。这是不幸的,因为我在很多不同的页面中使用当前的 AuthState 和类似的东西
<AuthorizeView Roles="@Utilisateur.Role_Abonne">
<Authorized>
<button class="LogButton" @onclick="Cancel">
<h5 class="LogButtonText">
Disconnect
</h5>
</button>
</Authorized>
<NotAuthorized>
<button class="LogButton">
<h5 class="LogButtonText" @onclick="Register">
Connect
</h5>
</button>
</NotAuthorized>
</AuthorizeView>
如何在不强制用户注销的情况下刷新 AuthState?
this user has the same issue 但未给出响应。
我目前的 hack,在用户重新加载页面之前一直有效
protected Task<AuthenticationState> NewTask;
public void RaiseAuthStateChanged(ClaimsPrincipal Claim)
{
NewTask = Task.FromResult(new AuthenticationState(Claim));
NotifyAuthenticationStateChanged(NewTask);
}
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
if (NewTask != null) return NewTask;
else return base.GetAuthenticationStateAsync();
}
但我觉得这很难看,我什至不知道这是否会引发安全问题。
【问题讨论】: