首页 > 解决方案 > 网络核心标识 2.1 中的方法 VerifyTwoFactorTokenAsync() 存在问题

问题描述

我正在使用 .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;
        }

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

解决方案


Xem thời gian máy chủ và thời gian của thiết bị có cái nào sai sai ko:

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

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

使用:与互联网时间服务器同步:time.nist.gov 不使用:time.windows.com


推荐阅读