两因素身份验证始终是无效代码

时间:2019-08-14 06:10:58

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

我已经设置了2fa,但始终会显示无效代码。

我已经在.net core 2.1和2.2上进行过尝试。但总是会说来自Google以及Microsoft身份验证器的无效代码。

//启用Authenticator.cshtml

<p>Scan the QR Code or enter this key <kbd>@Model.SharedKey</kbd> 
into your two factor authenticator app. Spaces and casing do not matter. 
</p>
<div class="alert alert-info">To enable QR code generation please 
read our <a href="https://go.microsoft.com/fwlink/? 
Linkid=852423">documentation</a>.</div>
<div id="qrCode"></div>
<div id="qrCodeData" data- 
url="@Html.Raw(@Model.AuthenticatorUri)"></div>
//Js in Enable Authenticator.cshtml
@section Scripts {
<partial name="_ValidationScriptsPartial" />
<script type="text/javascript" src="~/lib/qrcode.js"></script>
<script type="text/javascript">
new QRCode(document.getElementById("qrCode"),
{
text: "@Html.Raw(Model.AuthenticatorUri)",
width: 200,
height: 200
});
</script>
//Enable Authenticator.cshtml.cs
var user = await _userManager.GetUserAsync(User);
        if (user == null)
        {
            return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
        }

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

        // Strip spaces and hypens
        var verificationCode = Input.Code.Replace(" ", string.Empty).Replace("-", string.Empty);

        var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync(
            user, _userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode);

        if (!is2faTokenValid)
        {
            ModelState.AddModelError("Input.Code", "Verification code is invalid.");
            await LoadSharedKeyAndQrCodeUriAsync(user);
            return Page();
        }

        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);

        StatusMessage = "Your authenticator app has been verified.";

        if (await _userManager.CountRecoveryCodesAsync(user) == 0)
        {
            var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
            RecoveryCodes = recoveryCodes.ToArray();
            return RedirectToPage("./ShowRecoveryCodes");
        }
        else
        {
            return RedirectToPage("./TwoFactorAuthentication");
        }

我想设置身份验证,但是它始终是无效的代码。

2 个答案:

答案 0 :(得分:0)

我遇到了同样的情况,这是由于主机,我的PC和测试环境的时间与我的手机相距2分钟之间隔造成的。
time.windows.com无法用于时间同步。

答案 1 :(得分:0)

我知道这是一个较旧的主题,但是我遇到了同样的问题。

最后,我的_userManager.Options.Tokens.AuthenticatorTokenProvider从通过电子邮件执行2fa的一些旧代码中被错误地设置为“电子邮件”。

因此,请确保_userManager.Options.Tokens.AuthenticatorTokenProvider未更改(默认为“ Authenticator”)

也许会帮助某人!