我继承了一个用 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)