c# - 网络核心标识 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;
}
解决方案
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
推荐阅读
- android - Cardview 阴影在 ScrollView 中看起来不同
- python - python中的“IndexError:列表索引超出范围”错误
- encryption - 无法使用 openssl 加密私钥
- kubernetes - 如何使用私有注册表提供程序,服务帐户 - 来自 Kubernertes 部署
- powershell - ACL 的 PowerShell SetAccessRule 失败
- azure - Azure App Service 对不同的应用服务实例给出了另一个响应
- sql - 如何对有差距的后续数据进行排名
- distributed-computing - 您将如何构建一个三层 Web 应用程序来限制停机时间?
- pycharm - 即使 PyCharm 已经在运行,也要运行 PyCharm inspect.sh
- variables - 将变量传递给子组件