【问题标题】:Server-side Blazor 5.0 cascading AuthState not updating服务器端 Blazor 5.0 级联 AuthState 未更新
【发布时间】: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();
}

但我觉得这很难看,我什至不知道这是否会引发安全问题。

【问题讨论】:

    标签: c# blazor identity roles


    【解决方案1】:

    我认为需要注销并重新登录以查看更新的角色等的用户是一个已知问题/限制。

    我当然记得在播客等中讨论过的问题。

    【讨论】:

      猜你喜欢
      • 2020-07-26
      • 2021-10-07
      • 2020-07-17
      • 2023-02-17
      • 2020-09-02
      • 2021-05-28
      • 2020-05-15
      • 2020-04-29
      • 1970-01-01
      相关资源
      最近更新 更多