public async Task <IActionResult> EnableMfa() { var user = await _userManager.GetUserAsync(User); if (user.PasswordHash == null) { return(RedirectToAction("Index", "AccountManage")); } var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); if (string.IsNullOrEmpty(unformattedKey)) { await _userManager.ResetAuthenticatorKeyAsync(user); unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); } var sharedKey = unformattedKey.ToLowerInvariant(); var email = await _userManager.GetEmailAsync(user); var qrCodeUri = GenerateQrCodeUri(email, unformattedKey); var accountMfaInformation = new AccountMfaInformation { SharedKey = sharedKey, QrlCodeUri = qrCodeUri }; return(View(accountMfaInformation)); }
public async Task <IActionResult> EnableMfa(AccountMfaInformation accountMfaInformation) { if (ModelState.IsValid) { if (!string.IsNullOrEmpty(accountMfaInformation.VerifyCode)) { var verifyCode = accountMfaInformation.VerifyCode.Replace(" ", string.Empty).Replace("-", string.Empty); var authenticatorProvider = _userManager.Options.Tokens.AuthenticatorTokenProvider; var user = await _userManager.GetUserAsync(User); var isVerifyCodeValid = await _userManager.VerifyTwoFactorTokenAsync(user, authenticatorProvider, verifyCode); if (isVerifyCodeValid) { await _userManager.SetTwoFactorEnabledAsync(user, true); ViewData["Message"] = "Your authenticator app has been verified."; if (await _userManager.CountRecoveryCodesAsync(user) == 0) { var codes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10); var recoveryCodes = new StringBuilder(); foreach (var code in codes) { recoveryCodes.Append(code).Append(" "); } ViewData["RecoveryCodes"] = " In case of you lost your mobile phone, write down 10 recovery codes below. \r\n" + recoveryCodes.ToString(); return(View(accountMfaInformation)); } return(View(accountMfaInformation)); } } ModelState.AddModelError(string.Empty, "invalid verify code."); return(View(accountMfaInformation)); } ModelState.AddModelError(string.Empty, "invalid mfa registration."); return(View(accountMfaInformation)); }