Search code examples
c#asp.net-core.net-coreidentityserver4two-factor-authentication

RedirectToAction starts new session


I have a controller which logins in my user. Assuming its an existing user and the password is correct i check if they have 2fa enabled.

AccountControler login method

public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, set lockoutOnFailure: true
            var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, _configurationSettings.LockoutOnFailure);
            if (result.Succeeded)
            {
                var user = await _userManager.FindByEmailAsync(model.Email);
                await _signInManager.SignInAsync(user, _configurationSettings.IsPersistent);
                _logger.LogInformation("User logged in.");
                return RedirectToLocal(returnUrl);
            }
            if (result.RequiresTwoFactor)
            {
                return RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe });
            }
            if (result.IsLockedOut)
            {
                _logger.LogWarning("User account locked out.");
                return RedirectToAction(nameof(Lockout));
            }

            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
            return View(model);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

Assuming the user does have 2fa enabled then i redirect them to the LoginWith2fa method.

  [HttpGet]
    [AllowAnonymous]
    public async Task<IActionResult> LoginWith2fa(bool rememberMe, string returnUrl = null)
    {
        // Ensure the user has gone through the username & password screen first
        var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();

        if (user == null)
        {
            throw new ApplicationException($"Unable to load two-factor authentication user.");
        }

        var model = new LoginWith2faViewModel { RememberMe = rememberMe };
        ViewData["ReturnUrl"] = returnUrl;

        return View(model);
    }

This is where my problem comes in var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); always returns null. I put a few break points in and it looks like its recaling my constructers both in ApplicationSignInManager and the AccountController. There by giving me a new session.

SignInManager is registered as scoped in startup.cs

services.AddIdentity<ApplicationUser, IdentityRole<long>>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddSignInManager<ApplicationSignInManager>()
            .AddDefaultTokenProviders();

How do you call RedirectToAction and retain the same session?

I have been following this project Identity Server 4 Demo

Update: Comment about HttpContext enter image description here


Solution

  • Thanks to @muqeetkhan for giving me the hint. Becouse i am using a custom SignInManager it needs to set the proper session cookies in order for the user data to be propagated to the next page.

    public class ApplicationSignInManager : SignInManager<ApplicationUser>
        {
    
            private readonly ILogger _logger;
            public ApplicationSignInManager(UserManager<ApplicationUser> userManager, IHttpContextAccessor contextAccessor, IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory, IOptions<IdentityOptions> optionsAccessor,
                ILogger<ApplicationSignInManager> logger, IAuthenticationSchemeProvider schemes) : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemes)
            {
                _logger = logger;
            }
    
            public override async Task<SignInResult> PasswordSignInAsync(string userEmail, string password, bool isPersistent, bool shouldLockout)
            {
                if (UserManager == null)
                    return SignInResult.Failed;
                var result = await new FindUserCommand(_logger, UserManager, userEmail, password, shouldLockout).Execute();
    
                if (result != SignInResult.TwoFactorRequired) return result;
    
                var user = await UserManager.FindByEmailAsync(userEmail);
                return await SignInOrTwoFactorAsync(user, true);   // Required sets the session Cookie
            }
        }
    

    Basically SignInOrTwoFactorAsync(user, true); needs to be called.