带有 IsAuthenticated false OWIN 的 MVC AccountController

MVC AccountController with IsAuthenticated false OWIN

我有一个带有登录操作的 AccountController。

我们像这样在我们的应用程序服务中登录用户:

_signInManager.AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = userDto.RememberMe }, identity);

之后我将用户重定向到 Home/Index。

在 Home/Index 中 User.IsAuthenticated 是 true

但是在执行此重定向之前,在 AccountController 中,即使在调用 _signInManager.AuthenticationManager.SignIn(...) User.IsAuthenticated 之后也是 false.

我们做错了什么?

问题是,我需要对 AccountController 进行单元测试,并想测试调用 _signInManager.AuthenticationManager.SignIn(...) 后用户是否真的登录了。

非常感谢您的帮助

丹尼尔

编辑:

使用此代码后:

            ClaimsPrincipal principal = new ClaimsPrincipal(identity);
            System.Threading.Thread.CurrentPrincipal = principal;
            HttpContext.Current.User = principal;

工作正常,但闻起来很奇怪!

这是因为基于用户浏览器 cookie 的身份验证。您需要将客户端重定向到用户代理(浏览器)并在新请求中发送 cookie,然后您的应用才能进行身份验证。

看看这个link:ASP.NET Identity AuthenticationManager vs. SignInManager and cookie expiration

您正在使用 AuthenticationManager,我相信您的代码是这样的:

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);

    var identity = await UserManager.CreateIdentityAsync(
       user, DefaultAuthenticationTypes.ApplicationCookie);

    AuthenticationManager.SignIn(
       new AuthenticationProperties() { 
          IsPersistent = isPersistent 
       }, identity);
}

您可以使用 SignInManager。它的 PasswordSignInAsync 方法 returns 一个 SingInStatus 结果。在这种情况下,您的代码应该是这样的:

var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }

要查看如何使用它,请确保您拥有最新版本的 visual studio 2013 并创建一个新的 asp.net Web 应用程序项目,使用 "Individual User Accounts" 作为 "Authentication Type"