小编Ste*_*ock的帖子

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

我继承了一个用 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; …
Run Code Online (Sandbox Code Playgroud)

asp.net-identity asp.net-core blazor blazor-server-side

4
推荐指数
1
解决办法
3815
查看次数