locked
.AspNet.TwoFactorRememberBrowser cookie is not being set RRS feed

  • Question

  • User-1188570427 posted


    The two <g class="gr_ gr_16 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar multiReplace" id="16" data-gr-id="16">factor</g> remember browser cookie is not being set:
    The Expires / Max-Age in Chrome is: N/A

    Here is my SignInAsync():

     await SignInAsync(user, isPersistent, true);

    If I change isPersistent to TRUE, it works for both the two <g class="gr_ gr_73 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar multiReplace" id="73" data-gr-id="73">factor</g> remember browser and my UserCookie Authentication
    Here is my code:

    // Enable the application to use a cookie to store information for the signed in user
    // and to use a cookie to temporarily store information about a user logging in with a third party login provider
    // Configure the sign in cookie
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
    AuthenticationType = defaultAuth,
    LoginPath = logInPath,
    CookieName = MiddlewareConstants.Cookie,
    CookieSecure = CookieSecureOption.Always,
    SlidingExpiration = true,
    ExpireTimeSpan = TimeSpan.FromMinutes(sessionTimeout)
    });
    //// If we are Identity, set up user UseCookieAuthentication for TwoFactorRememberBrowserCookie
    if (authenticationType == SharedConstants.Identity)
    {
    // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
    app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
    
    var rememberBrowserCookieType = DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie;
    
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
    AuthenticationType = rememberBrowserCookieType,
    AuthenticationMode = AuthenticationMode.Passive,
    CookieName = &quot;.AspNet.&quot; &#43; rememberBrowserCookieType,
    ExpireTimeSpan = TimeSpan.FromDays(30)
    });
    }




    Should I HAVE to set <g class="gr_ gr_19 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="19" data-gr-id="19">isPersistent</g> to TRUE for this to work?
    I thought the <g class="gr_ gr_14 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling multiReplace" id="14" data-gr-id="14">log in</g> <g class="gr_ gr_12 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" id="12" data-gr-id="12">cookie</g> should run off session.
    and the TwoFactor cookie should be persisted so it stays in the browser?

    Wednesday, April 10, 2019 9:29 PM

Answers

All replies

  • User-1811426859 posted

    Do you have same problem with  https://stackoverflow.com/a/32168617/5751404  ?

    Thursday, April 11, 2019 9:26 AM
  • User475983607 posted

    Can you explain your expectation and what actually happens?

    I'm thinking that Two Factor Auth in ASP.NET Identity does not work as you expect.  The end result of two factor auth is an authentication cookie.  The auth cookie is not created until the user successfully navigates the second authentication step. 

    Thursday, April 11, 2019 12:18 PM
  • User-1188570427 posted

    Can you explain your expectation and what actually happens?

    I'm thinking that Two Factor Auth in ASP.NET Identity does not work as you expect.  The end result of two factor auth is an authentication cookie.  The auth cookie is not created until the user successfully navigates the second authentication step. 

    So when should that cookie actually be made?

    So Here are my steps:

    1. Validate their password with SignInAsync()
    2. Navigate them to a View that will send out a verification code
    3. Wait for them to successfully validate that code
    4. Then send them to the Index Home View once they validate that.

    I've tried TwoFactorySignInAsync, but it does not work. It fails every time.  I think I saw some code for that method and maybe I just need to wait until I validate the two factor verification code to sign them in?

    Thursday, April 11, 2019 12:51 PM
  • User-1188570427 posted

    Do you have same problem with  https://stackoverflow.com/a/32168617/5751404  ?

    Yes, it is very similar. I just can't get it set up properly etc.

    Thursday, April 11, 2019 1:02 PM
  • User475983607 posted

    So when should that cookie actually be made?

    So Here are my steps:

    1. Validate their password with SignInAsync()
    2. Navigate them to a View that will send out a verification code
    3. Wait for them to successfully validate that code
    4. Then send them to the Index Home View once they validate that.

    I've tried TwoFactorySignInAsync, but it does not work. It fails every time.  I think I saw some code for that method and maybe I just need to wait until I validate the two factor verification code to sign them in?

    The ASP.NET Identity template that comes with Visual Studio works.  Have you written custom code?

    I've tried TwoFactorySignInAsync, but it does not work. It fails every time

    The method returns an error.

            // POST: /Account/VerifyCode
            [HttpPost]
            [AllowAnonymous]
            [ValidateAntiForgeryToken]
            public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
            {
                if (!ModelState.IsValid)
                {
                    return View(model);
                }
    
                // The following code protects for brute force attacks against the two factor codes. 
                // If a user enters incorrect codes for a specified amount of time then the user account 
                // will be locked out for a specified amount of time. 
                // You can configure the account lockout settings in IdentityConfig
                var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent:  model.RememberMe, rememberBrowser: model.RememberBrowser);

    What is the error?

    Thursday, April 11, 2019 1:32 PM
  • User-1188570427 posted

    tvb2727

    So when should that cookie actually be made?

    So Here are my steps:

    1. Validate their password with SignInAsync()
    2. Navigate them to a View that will send out a verification code
    3. Wait for them to successfully validate that code
    4. Then send them to the Index Home View once they validate that.

    I've tried TwoFactorySignInAsync, but it does not work. It fails every time.  I think I saw some code for that method and maybe I just need to wait until I validate the two factor verification code to sign them in?

    The ASP.NET Identity template that comes with Visual Studio works.  Have you written custom code?

    tvb2727

    I've tried TwoFactorySignInAsync, but it does not work. It fails every time

    The method returns an error.

            // POST: /Account/VerifyCode
            [HttpPost]
            [AllowAnonymous]
            [ValidateAntiForgeryToken]
            public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
            {
                if (!ModelState.IsValid)
                {
                    return View(model);
                }
    
                // The following code protects for brute force attacks against the two factor codes. 
                // If a user enters incorrect codes for a specified amount of time then the user account 
                // will be locked out for a specified amount of time. 
                // You can configure the account lockout settings in IdentityConfig
                var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent:  model.RememberMe, rememberBrowser: model.RememberBrowser);

    What is the error?

    Hey, it just fails every time. It always has failed etc.

    Thursday, April 11, 2019 1:49 PM
  • User475983607 posted

    tvb2727

    Hey, it just fails every time. It always has failed etc.

    Unclear.  It returns 3?  If so, what are the values of the input parameter properties?  Have you verified the View Fields are populated?

    public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)

    I Is there anyway you can post example code that reproduces this issue?  This will allow us to find the bug.

    Thursday, April 11, 2019 1:53 PM
  • User-1188570427 posted

    tvb2727

    Hey, it just fails every time. It always has failed etc.

    Unclear.  It returns 3?  If so, what are the values of the input parameter properties?  Have you verified the View Fields are populated?

    public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)

    I Is there anyway you can post example code that reproduces this issue?  This will allow us to find the bug.

    Yes, I get the code properly and all the fields are populated fine.  I'm actually doing it a little custom.

    What is the process of SignIn with Two Factor?

    I'm also seeing an issue where the two factor sign in cookie is not being generated. I need that to be generated so I can go get my code and I need it to expire after 3 minutes etc.

    Maybe that is my issue?

    I have this code to see if I need to check for two factor etc. This is when I am signing in and validating the password etc.

            public async Task<CustomSignInStatus> CustomPasswordSignInAsync(string email, string password, bool isPersistent)
            {
                if (UserManager == null)
                {
                    return CustomSignInStatus.Failure;
                }
    
                var user = await UserManager.FindByEmailAsync(email);
    
                if (user == null)
                {
                    return CustomSignInStatus.Failure;
                }
    
                if (UserManager.SupportsUserLockout && UserManager.IsLockedOut(user.Id))
                {
                    return CustomSignInStatus.LockedOut;
                }
    
                using (var service = new UserService())
                {
                    var myappUser = await service.GetUser(user.myappUserId).ConfigureAwait(false);
    
                    if (myappUser.SoftDeletedDate != null)
                    {
                        return CustomSignInStatus.AccountIsDeactivated;
                    }
    
                    bool isAuth = await UserManager.CheckPasswordAsync(user, password);
                    if (!isAuth)
                    {
                        if (UserManager.SupportsUserLockout && UserManager.GetLockoutEnabled(user.Id))
                        {
                            UserManager.AccessFailed(user.Id);
                        }
    
                        return CustomSignInStatus.Failure;
                    }
                    else
                    {
                        if (UserManager.SupportsUserLockout && UserManager.GetAccessFailedCount(user.Id) > 0)
                        {
                            UserManager.ResetAccessFailedCount(user.Id);
                        }
                    }
    
                    bool isEmailConfirmed = await UserManager.IsEmailConfirmedAsync(user.Id);
                    if (!isEmailConfirmed)
                    {
                        return CustomSignInStatus.RequiresVerification;
                    }
    
                    if (!myappUser.IsApproved)
                    {
                        return CustomSignInStatus.NotActive;
                    }
    
                    if (user.LastPasswordChangeDate.AddDays(PasswordExpireDays) < DateTime.UtcNow)
                    {
                        return CustomSignInStatus.PasswordExpired;
                    }
    
                    if (UserManager.SupportsUserTwoFactor)
                    {
                        bool isMfaConfirmed = await AuthenticationManager.TwoFactorBrowserRememberedAsync(user.Id);
                        if (!isMfaConfirmed)
                        {
                            // Need to set this somehow? : 
                            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
                            //app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
                            return CustomSignInStatus.VerifyMFACode;
                        }
                    }
    
                    await SetLastLoginDate(UserManager, user);
                    await SignInAsync(user, isPersistent, false);
                    return CustomSignInStatus.Success;
                }
            }

    Thursday, April 11, 2019 2:57 PM
  • User475983607 posted

    Sorry, I was thinking about email validation.

    The Two Factor Tutorial is here...

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/security/aspnet-mvc-5-app-with-sms-and-email-two-factor-authentication

    Compare the tutorial implementation with your code.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 11, 2019 5:44 PM
  • User-1188570427 posted

    Sorry, I was thinking about email validation.

    The Two Factor Tutorial is here...

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/security/aspnet-mvc-5-app-with-sms-and-email-two-factor-authentication

    Compare the tutorial implementation with your code.

    Hey I got it working.

    The issue I was having was when I would redirect to action on the Verify MFA Code view...

    I did not have 

    [AllowAnonymous]

    on it and it was not validating because the control it was in had access attribute on top of it etc.

        [AuthorizationBase]

    Everything seems to be working except the authentication cookie keeps sliding even though no activity is going on the website from the end user standpoint. I need to track that issue down now.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 11, 2019 9:08 PM