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

时间:2020-03-22 18:19:07

标签: asp.net-core asp.net-identity blazor blazor-server-side

我继承了一个用Blazor和.NET Core 3.1编写的网站,我需要向用户提供一个“注销”按钮。该网站使用AuthenticationStateProvider的自定义实现以及以下listen EADDRINUSE: address already in use :::3000 方法:

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) { ... } 方法中,该方法在单击“注销”链接时执行。我正在从Blazor的会话存储中删除“用户”会话,但是当调用Logout()时,它仍返回为principal.Identity.IsAuthenticated吗?

有人知道注销时如何将true设置为IsAuthenticated吗?

1 个答案:

答案 0 :(得分:4)

原则上,您的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的构造函数。