AuthenticationManager.SignIn()没有成功进行登录。

7

我可以从数据库中获取有效的用户,创建ClaimsIdentity,并且在调用SignIn方法时没有错误发生。

public ActionResult SignInConformation(SignInModel model)
{
    if (ModelState.IsValid)
    {
        var user = _userManager.Find(model.Username, model.Password);

        if (user == null)
        {
            ModelState.AddModelError("", "Invalid username and\\or password");
        }
        else
        {
            _authenticationManager.SignOut();
            var claimsIdentity = _userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
            _authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, claimsIdentity);
            return RedirectToAction("Index", "Home");
        }
    }

    return View();
}

然而,当我在视图中检查用户是否已登录时,代码如下:
<p>
    Current User: @if (User.Identity.IsAuthenticated)
                  {
                      @User.Identity.Name
                  }
                  else
                  {
                      @:Unknown
                  }
</p>

IsAuthenticated 返回 false

2个回答

12

OWIN启动类中缺少AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie

var authenticationOptions = new CookieAuthenticationOptions
{
    LoginPath = new PathString("/Account/SignIn"),
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
};

appBuilder.UseCookieAuthentication(authenticationOptions);

没有一个好的、有用的错误提示真是太遗憾了。我不喜欢程序默默失败。


我目前遇到了同样的问题,生产环境运行良好,没有问题(指从开发机器连接到生产数据库),但是开发环境不再工作。我已经检查了上述内容,但在启动类中出现了这个问题。 - Jean-Paul
你节省了我大量的时间,OWIN的Authentication.SignIn没有为我更改CurrentPrincipal,所以我不得不用这种方式来解决。谢谢。 - Vedran Mandić
请注意,DefaultAuthenticationTypes.ApplicationCookie在AspNet.Identity中定义。如果您想避免引用它,您可以将其设置为“ApplicationCookie”。 - Christopher Elliott

0

我有同样的问题 - 问题在于我的主控制器受到 [Authorize(Roles = "Administrator")] 属性的保护,而我正在尝试以用户身份登录。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接