public async Task <IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User).ConfigureAwait(false); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } var isTwoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user).ConfigureAwait(false); var userId = await _userManager.GetUserIdAsync(user).ConfigureAwait(false); if (!isTwoFactorEnabled) { throw new InvalidOperationException($"Cannot generate recovery codes for user with ID '{userId}' as they do not have 2FA enabled."); } var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10).ConfigureAwait(false); RecoveryCodes.AddRange(recoveryCodes); _logger.LogInformation(_localizer["User with ID '{UserId}' has generated new 2FA recovery codes."], userId); StatusMessage = "You have generated new recovery codes."; return(RedirectToPage("./ShowRecoveryCodes")); }
public async Task <IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User).ConfigureAwait(false); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } if (!ModelState.IsValid) { await LoadSharedKeyAndQrCodeUriAsync(user).ConfigureAwait(false); return(Page()); } // Strip spaces and hypens var verificationCode = Input.Code.Replace(" ", string.Empty, StringComparison.InvariantCultureIgnoreCase) .Replace("-", string.Empty, StringComparison.InvariantCultureIgnoreCase); var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync( user, _userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode).ConfigureAwait(false); if (!is2faTokenValid) { ModelState.AddModelError("Input.Code", "Verification code is invalid."); await LoadSharedKeyAndQrCodeUriAsync(user).ConfigureAwait(false); return(Page()); } await _userManager.SetTwoFactorEnabledAsync(user, true).ConfigureAwait(false); var userId = await _userManager.GetUserIdAsync(user).ConfigureAwait(false); _logger.LogInformation(_localizer["User with ID '{UserId}' has enabled 2FA with an authenticator app."], userId); StatusMessage = "Your authenticator app has been verified."; if (await _userManager.CountRecoveryCodesAsync(user).ConfigureAwait(false) == 0) { var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10).ConfigureAwait(false); RecoveryCodes.AddRange(recoveryCodes.ToList()); return(RedirectToPage("./ShowRecoveryCodes")); } else { return(RedirectToPage("./TwoFactorAuthentication")); } }
public IActionResult OnGet() { return(RecoveryCodes is null || RecoveryCodes.Any() ? RedirectToPage("./TwoFactorAuthentication") : (IActionResult)Page()); }