locked
Two Factor Authentication, VerifyTwoFactorTokenAsync always return false RRS feed

  • Question

  • User-1013792694 posted

    I tried creating a new project from VS 2017 (.Net Core v2.0) and for authentication, I chose 'Individual User Accounts'. I put QRCode from (<cite class="iUh30">https://davidshimjs.github.io/qrcodejs/</cite>). I put javascript code in EnableAuthenticator.cshtml

        <script src="~/lib/qcrcode.js/qrcode.js"></script>
        <script>
            new QRCode(document.getElementById("qrCode"),
                {
                    text: "@Html.Raw(Model.AuthenticatorUri)",
                    width: 200,
                    height: 200
                }
            );
        </script>


    In ManageController.cs, action method EnableAuthenticator doesn't change at all.

            [HttpPost]
            [ValidateAntiForgeryToken]
            public async Task<IActionResult> EnableAuthenticator (EnableAuthenticatorViewModel model) {
                var user = await _userManager.GetUserAsync(User);
                if ( user == null ) {
                    throw new ApplicationException ($"Unable to load user with ID '{_userManager.GetUserId (User)}'.");
                }
    
                if ( !ModelState.IsValid ) {
                    await LoadSharedKeyAndQrCodeUriAsync (user, model);
                    return View (model);
                }
    
                // Strip spaces and hypens
                var verificationCode = model.Code.Replace(" ", string.Empty).Replace("-", string.Empty);
    
                //AuthenticatorTokenProvider
                var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync(
                    user, _userManager.Options.Tokens.EmailConfirmationTokenProvider, verificationCode);
    
                if ( !is2faTokenValid ) {
                    ModelState.AddModelError ("Code", "Verification code is invalid.");
                    await LoadSharedKeyAndQrCodeUriAsync (user, model);
                    return View (model);
                }
    
                await _userManager.SetTwoFactorEnabledAsync (user, true);
                _logger.LogInformation ("User with ID {UserId} has enabled 2FA with an authenticator app.", user.Id);
                var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
                TempData[RecoveryCodesKey] = recoveryCodes.ToArray ();
    
                return RedirectToAction (nameof (ShowRecoveryCodes));
            }

    and this is QRCode generator

            private async Task LoadSharedKeyAndQrCodeUriAsync (ApplicationUser user, EnableAuthenticatorViewModel model) {
                var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
                if ( string.IsNullOrEmpty (unformattedKey) ) {
                    await _userManager.ResetAuthenticatorKeyAsync (user);
                    unformattedKey = await _userManager.GetAuthenticatorKeyAsync (user);
                }
    
                model.SharedKey = FormatKey (unformattedKey);
                model.AuthenticatorUri = GenerateQrCodeUri (user.Email, unformattedKey);
            }

    I run and register user, I get notification to 'update-database' to be executed in Package manager console, done. I register again and login successfully. In the 'Two-factors Authentication' menu, I clicked 'configure authentication app', go to 'enable authenticator' page scan QRCode through google/microsoft authenticator and always get fail with this error message: Verification code is valid

    I tried to debug, I found VerifyTwoFactorTokenAsync() always return false. I don't know why this happen ? I tried to changed AuthenticatorTokenProvider became EmailConfirmationTokenProvider and still return false.

    but I found something interesting that [TwoFactorEnabled] and [EmailConfirmed] columns in the dbo.AspNetUsers is false. 

    are there any relation between value in the [TwoFactorEnabled] and [EmailConfirmed] columns and VerifyTwoFactorTokenAsync(), because one of the parameter is ApplicationUser ?

    how to solve this problem ?

    Thursday, June 20, 2019 9:23 AM

Answers

  • User-1764593085 posted

    Hi daleman,

    It's strange. For my localhost app. I download aMicrosoft  Authenticator App and select work/school account to scan the QR code.It generates a correct verification code...

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 26, 2019 10:02 AM

All replies

  • User-1764593085 posted

    Hi daleman,

    I could not reproduce your problem by generating Verification Code from https://gauth.apps.gbraad.nl/, you could refer to below tutorial to have a test, it is more likely that your Verification Code is not correct:

    https://www.c-sharpcorner.com/article/setting-up-two-factor-authentication-in-asp-net-core-2-0/

    but I found something interesting that [TwoFactorEnabled] and [EmailConfirmed] columns in the dbo.AspNetUsers is false. 

    Because you have not confirmed email and set two factor auth to them yet, their definition is

    public class IdentityUser<TKey> where TKey : IEquatable<TKey>
        {
           
            //
            // Summary:
            //     Gets or sets a flag indicating if two factor authentication is enabled for this
            //     user.
            public virtual bool TwoFactorEnabled { get; set; }
                
            //
            // Summary:
            //     Gets or sets a flag indicating if a user has confirmed their email address.
            public virtual bool EmailConfirmed { get; set; }
            
            //other fields
        }

    When VerifyTwoFactorTokenAsync() returns true, the TwoFactorEnabled is set to true.

    Best Regards,

    Xing

    Friday, June 21, 2019 6:42 AM
  • User-1013792694 posted

    Xing, thank you for your response. I just tried making a new project, the connectiong binding to 'Server=(localdb)\\mssqllocaldb' and everything works fine => follow your link.

    But when I tried to authenticate via Google Auth / Microsoft Auth the message error came out "Verification code is invalid." The issue is VerfyTwoFactorTokenAsyn always return false. I don't know why this could happen. Xing, any idea ?

    Why Google & Microsoft Auth  can't validate the QRcode ? What's mobile app I should install to Authenticate process ?

    Monday, June 24, 2019 3:56 AM
  • User-1764593085 posted

    Hi daleman,

    I could not reproduce the problem.It still works when I use DataSource like

    "ConnectionStrings": {
        "DefaultConnection":"DataSource=testdatabase.db"
      },

    Configureservice:

    services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

    Remove the existing Migration folder and add migration and update database again.

    Best Regards,

    Xing

    Monday, June 24, 2019 7:14 AM
  • User-1013792694 posted

    Hi Xing,

    Connection string works fine and for gauth.apps.gbraad.nl can produce an authenticate code, match with QRcode. 

    As my last question, Why Google & Microsoft Auth app  can't validate the QRcode ? The issue is VerfyTwoFactorTokenAsyn always return false.

    Meanwhile gauth.apps.gbraad.nl can validate easily.

    Rgds,

    Monday, June 24, 2019 9:25 AM
  • User-1764593085 posted

    Hi daleman,

    I never used the Auth app but it is possibly that the auth app could not recognize your localhost app,maybe they need on the same public network.

    I would suggest that you could mark the answer to close the thread and post new question in another thread.Then more communities could see and answer this question.

    Best Regards,

    Xing

    Monday, June 24, 2019 10:14 AM
  • User-1013792694 posted

    Hi Xing,

    the actual local host can't recognize the QRcode but the gauth.apps.gbraad.nl/#main  can generate code correctly. For me, It's sound doesn't make sense.

    _____

    As your suggestion, I just deployed in Azure but QRcode still  remain 'Verification code is invalid' via (google & microsoft)

    But gauth.apps.gbraad.nl/#main can generate QRcode correctly.

    Monday, June 24, 2019 10:21 AM
  • User-1764593085 posted

    Hi daleman,

    It's strange. For my localhost app. I download aMicrosoft  Authenticator App and select work/school account to scan the QR code.It generates a correct verification code...

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 26, 2019 10:02 AM