public async Task <IActionResult> EnableAuthenticator([FromBody] EnableAuthenticatorDto model) { var user = await _userManager.GetUserAsync(User); if (user == null) { return(BadRequest($"Unable to load user with ID '{_userManager.GetUserId(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(Ok(model)); } await _userManager.SetTwoFactorEnabledAsync(user, true); _logger.LogInfo($"User {user.UserName} with has enabled 2fa."); return(Ok()); }
private async Task LoadSharedKeyAndQrCodeUriAsync(User user, EnableAuthenticatorDto 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.GetUserAsync(User); if (user == null) { return(BadRequest($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } var model = new EnableAuthenticatorDto(); await LoadSharedKeyAndQrCodeUriAsync(user, model); return(Ok(model)); }