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

Ste*_*ock 4 asp.net-identity asp.net-core blazor blazor-server-side

我继承了一个用 Blazor 和 .NET Core 3.1 编写的网站,我需要向用户提供一个“注销”按钮。该网站使用 的自定义实现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));
}
Run Code Online (Sandbox Code Playgroud)

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

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

if (principal.Identity.IsAuthenticated)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

问题出在Logout()我编写的方法中,该方法在单击“注销”链接时执行。我正在从 Blazor 的会话存储中删除“用户”会话,但是当principal.Identity.IsAuthenticated调用时,它仍然返回为true?

有谁知道注销时如何设置IsAuthenticatedfalse

Isa*_*aac 7

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

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

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

\n

  • 您好,如果您发布了注销功能如何删除用户以及如何简化 GetAuthenticationStatAsync ,那么整个解决方案就在这里,那就太好了。我有同样的问题,但这篇文章只提供了部分答案。 (2认同)