2

I have an AccountController with a Login action.

We SignIn the user in our Application Service like that:

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

After that I redirect the user to Home/Index.

In the Home/Index the User.IsAuthenticated is true

But before doing this redirection, in the AccountController, even after calling _signInManager.AuthenticationManager.SignIn(...) User.IsAuthenticated is false.

What are we doing wrong?

Problem is, that I need to unit test the AccountController and want to test if after calling _signInManager.AuthenticationManager.SignIn(...), the user is really signed in.

Thank you very much for the help

Daniel

EDIT:

After using this code:

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

Works fine, but smells weird!

DAG
  • 2,460
  • 5
  • 33
  • 61

2 Answers2

2

This is because authentications based on user's browser cookie. You need a redirect commend to the client to user agent (browser) send the cookie in the new request, then your app could authenticate.

Sam FarajpourGhamari
  • 14,601
  • 4
  • 52
  • 56
1

Take a look at this link: ASP.NET Identity AuthenticationManager vs. SignInManager and cookie expiration

You are using AuthenticationManager, I believe your code is something like this:

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);
}

You can use SignInManager. Its PasswordSignInAsync method returns a SingInStatus result. In that case, your code should be something like this:

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);
        }

To see how to use it, make sure you have the latest version of visual studio 2013 and create a new asp.net web application project, using "Individual User Accounts" as "Authentication Type"

Community
  • 1
  • 1
Fabio
  • 11,892
  • 1
  • 25
  • 41