private async Task LoadSharedKeyAndQrCodeUriAsync(User user, EnableAuthenticatorResponse model) { var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); if (string.IsNullOrEmpty(unformattedKey)) { await _userManager.ResetAuthenticatorKeyAsync(user); unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); } model.SharedKey = FormatKey(unformattedKey); model.AuthenticatorUri = GenerateQrCodeUri(user.Email, unformattedKey); }
public async Task <IActionResult> EnableAuthenticator() { var user = await _userManager.FindByIdAsync(User.FindFirst("id")?.Value); if (user == null) { return(BadRequest(new string[] { "Could not find user!" })); } var model = new EnableAuthenticatorResponse(); await LoadSharedKeyAndQrCodeUriAsync(user, model); return(Ok(model)); }
public async Task <IActionResult> EnableAuthenticator([FromBody] EnableAuthenticatorResponse model) { var user = await _userManager.FindByIdAsync(User.FindFirst("id")?.Value); if (user == null) { return(BadRequest(new string[] { "Could not find user!" })); } if (!ModelState.IsValid) { await LoadSharedKeyAndQrCodeUriAsync(user, model); return(Ok(model)); } // 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("Code", "Verification code is invalid."); await LoadSharedKeyAndQrCodeUriAsync(user, model); return(View(model)); } await _userManager.SetTwoFactorEnabledAsync(user, true); var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10); return(Ok(recoveryCodes.ToArray())); }