我遵循了Pluralsight上的“ Asp.Net Identity深潜”课程。在一个模块中,他展示了如何实现身份验证器。我按照他的指示进行,但是我的令牌验证仍然无效。
我已经尝试过使用多个用户和验证码。
生成令牌
[HttpGet]
[Authorize]
public async Task<IActionResult> RegisterAuthenticator() {
var user = await userManager.GetUserAsync(User);
var authenticatorKey = await userManager.GetAuthenticatorKeyAsync(user);
if (authenticatorKey == null) {
await userManager.ResetAuthenticatorKeyAsync(user);
authenticatorKey = await userManager.GetAuthenticatorKeyAsync(user);
}
var qrcodeuri = "otpauth://totp/Guestbook:" + user.Email + "?secret=" + authenticatorKey;
return View(new RegisterAuthenticatorModel {
AuthenticatorKey = authenticatorKey,
QRCodeUri = qrcodeuri
});
}
检查令牌
[HttpPost]
[Authorize]
public async Task<IActionResult> RegisterAuthenticator(RegisterAuthenticatorModel model)
{
var user = await userManager.GetUserAsync(User);
var isValid = await userManager.VerifyTwoFactorTokenAsync(user,
userManager.Options.Tokens.AuthenticatorTokenProvider, model.Code);
if (!isValid)
{
ModelState.AddModelError("", "Code is invalid");
return View(model);
}
await userManager.SetTwoFactorEnabledAsync(user, true);
return View("Success");
}
我真的不知道问题出在哪里。