- 确认使用的认证方案是否正确,在 Startup.cs 文件中进行配置:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "Identity.Application";
options.DefaultChallengeScheme = "Identity.Application";
}).AddCookie("Identity.Application");
- 在认证成功后更新 AuthenticationStateProvider 中的 UserID,在 Login() 方法中添加以下代码:
var claims = new List
{
new Claim(ClaimTypes.NameIdentifier, user.Id)
};
var userIdentity = new ClaimsIdentity(claims, "login");
var userPrincipal = new ClaimsPrincipal(userIdentity);
await _httpContextAccessor.HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
userPrincipal);
- 确认 AuthenticationStateProvider 是否正确实现,例如:
public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
public override Task GetAuthenticationStateAsync()
{
// 获取当前用户的 UserID
var userId = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
// 如果 UserID 存在,返回已认证的状态
if (!string.IsNullOrEmpty(userId))
{
var claims = new List
{
new Claim(ClaimTypes.NameIdentifier, userId)
};
var identity = new ClaimsIdentity(claims, "login");
var principal = new ClaimsPrincipal(identity);
return Task.FromResult(new AuthenticationState(principal));
}
// 如果 UserID 为空,返回未认证的状态
return Task.FromResult(new AuthenticationState(new ClaimsPrincipal()));
}
}