AuthenticationManager.SignIn()未登录

时间:2015-10-25 14:48:28

标签: asp.net .net asp.net-mvc-3 asp.net-identity

我可以从数据库中获取有效用户,创建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 个答案:

答案 0 :(得分:9)

我错过了OWIN启动类中的AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie

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

appBuilder.UseCookieAuthentication(authenticationOptions);

遗憾的是,没有一个好的,有用的错误。我不喜欢无声无息的节目。

答案 1 :(得分:0)

我遇到了同样的问题-问题是我的Home控制器受到[Authorize(Roles =“ Administrator”)]属性的保护,而我试图以用户身份登录。