我在使用 Identity 和 cookie 的 ASP.NET Core MVC 应用程序中遇到身份验证问题。尽管使用 _signInManager.PasswordSignInAsync 成功登录,User.Identity.IsAuthenticated 仍返回 false。我已经检查了我的代码和设置,但无法确定根本原因。
public async Task<IActionResult> Login(SignInCommand model)
{
var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, false, false);
//return result;
// Access the current user's information
if(result.Succeeded)
{
var isAuthenticated = User.Identity.IsAuthenticated;
var currentUser = HttpContext.User;
var userId = currentUser.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var userName = currentUser.Identity?.Name;
return RedirectToAction("Index", "Home");
}
return View("Login", model);
}
我的程序.cs https://gist.github.com/otmanik/4e41b7c6bef023d6d0081026e10eedf1
谢谢
在该特定时间点,
false
的值是正确的,因为您的 User
未经过身份验证(尽管它们正在进行身份验证)。他们在访问 Login
方法时已/未经过身份验证。
尝试另一个需要
User
进行身份验证的端点(方法),并从那里检查值。假设身份验证成功,值为
var isAuthenticated = User.Identity.IsAuthenticated;
应该是
true
。
这应该通过在AddIdentity之前添加AddAuthentication来解决:
我移动了 builder.Services.AddAuthentication(options => ..
前
builder.Services.AddIdentity