我继承了一个用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
吗?
答案 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
的构造函数。