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?
有谁知道注销时如何设置IsAuthenticated?false
原则上,您的GetAuthenticationStateAsync方法应该类似于:
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 }\nRun Code Online (Sandbox Code Playgroud)\n\n注意:该GetTokenAsync方法从本地存储检索 JWT 令牌。如果它是空的,您将创建一个ClaimsIdentity没有声明的新对象。如果它不为空,则创建一个新ClaimsIdentity对象,其中包含您提供给它的声明,并且该对象将传递给ClaimsPrincipalxe2x80x99s 构造函数。
| 归档时间: |
|
| 查看次数: |
3815 次 |
| 最近记录: |