网络核心身份2.1中的方法VerifyTwoFactorTokenAsync()的问题

时间:2019-05-21 17:05:30

标签: c# asp.net-core-identity

我正在使用.Net Core Identity 2.1来启用带有qrcode的身份验证器。当我使用方法VerifyTwoFactorTokenAsync()并在localhost中运行时,它可以正常工作。但是,当我上传到主机时,它不起作用,并且is2faTokenValid始终返回false。 有谁遇到过类似的问题并找到了解决方案,或者知道我在哪里犯错了?

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> EnableAuthenticator(AuthenticatorModel model)
        {
            var user = await GetCurrentUserAsync();
            if (user == null)
            {
                return NotFound($"Not found user with Id '{_userManager.GetUserId(User)}'.");
            }

            if (!ModelState.IsValid)
            {
                await LoadSharedKeyAndQrCodeUriAsync(user);
                return View();
            }

            // Strip spaces and hypens
            var verificationCode = model.Code.Replace(" ", string.Empty).Replace("-", string.Empty);
            var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync(
                user, _userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode);  
            if (!is2faTokenValid)
            {

                ModelState.AddModelError("", "Invalid code.");
                var newmodel = await LoadSharedKeyAndQrCodeUriAsync(user);
                return View(newmodel);
            }

            await _userManager.SetTwoFactorEnabledAsync(user, true);
            var userId = await _userManager.GetUserIdAsync(user);
            _logger.LogInformation("User with ID '{UserId}' has enabled 2FA with an authenticator app.", userId);
            return Redirect("/Account/TwoFactorAuthentication");
        }
        private Task<AppUser> GetCurrentUserAsync()
        {
            return _userManager.GetUserAsync(User);
        }
        private async Task<AuthenticatorModel> LoadSharedKeyAndQrCodeUriAsync(AppUser user)
        {
            // Load the authenticator key & QR code URI to display on the form
            var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            if (string.IsNullOrEmpty(unformattedKey))
            {
                await _userManager.ResetAuthenticatorKeyAsync(user);
                unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            }            
            var model = new AuthenticatorModel();
            model.SharedKey = FormatKey(unformattedKey);
            var userName = await _userManager.GetUserNameAsync(user);
            model.AuthenticatorUri = GenerateQrCodeUri(userName, unformattedKey);
            return model;
        }

1 个答案:

答案 0 :(得分:0)

Xemthờigianmáychủvàthờigiancủathiếtbịcáinàosai sai ko:

TOTP客户端和服务器时间偏斜

TOTP(基于时间的一次性密码)身份验证取决于服务器和身份验证器设备是否具有正确的时间。令牌仅持续30秒。如果TOTP 2FA登录失败,请检查服务器时间是否正确,最好同步到准确的NTP服务。

使用:与Internet时间服务器同步:time.nist.gov 不要使用:time.windows.com