使用 AuthenticationStateProvider 注销用户并使用 Blazor 将 User.Identity.IsAuthenticated 设置为 false

Sign out a user using AuthenticationStateProvider and set User.Identity.IsAuthenticated to false using Blazor

我继承了一个用 Blazor 和 .NET Core 3.1 编写的网站,我需要向用户提供一个 "Logout" 按钮。该网站使用 AuthenticationStateProvider 的自定义实现,具有以下 GetAuthenticationStateAsync() 方法:

public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
    ClaimsIdentity identity = new ClaimsIdentity();

    if (_currentUser != null)
    {
        identity = GenerateClaimsForCurrentUser();
    }
    else
    {
        try
        {
            var user = await sessionStorage.GetItemAsync<Credentials>("User");
            if (user != null && await IsAuthentic(user))
            {
                _currentUser = await UserInfo(user);
                identity = GenerateClaimsForCurrentUser();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    return new AuthenticationState(new ClaimsPrincipal(identity));
}

验证用户是否登录,代码为:

AuthenticationState authState = await authenticationState.GetAuthenticationStateAsync();
ClaimsPrincipal principal = authState.User;

if (principal.Identity.IsAuthenticated)
{
    ...
}

问题出在我写的Logout()方法上,点击"Logout"link时执行。我正在从 Blazor 的会话存储中删除 "User" 会话,但是当调用 principal.Identity.IsAuthenticated 时,它仍然返回为 true?

有谁知道我如何在注销时将 IsAuthenticated 设置为 false

原则上,您的GetAuthenticationStateAsync方法应该类似于这样:

 public override async Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        var token = await GetTokenAsync();
        var identity = string.IsNullOrEmpty(token)
            ? new ClaimsIdentity()
            : new ClaimsIdentity(GenerateClaimsForCurrentUser(), "jwt");
        return new AuthenticationState(new ClaimsPrincipal(identity));
    }

注意:GetTokenAsync 方法从本地存储中检索 JWT 令牌。如果它为空,则创建一个没有声明的新 ClaimsIdentity 对象。如果它不为空,则创建一个新的 ClaimsIdentity 对象,其中包含您提供给它的声明,并将该对象传递给 ClaimsPrincipal 的构造函数。