EnableAuthenticator.cshtml.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. #nullable disable
  4. using System;
  5. using System.ComponentModel.DataAnnotations;
  6. using System.Globalization;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Text.Encodings.Web;
  10. using System.Threading.Tasks;
  11. using bitforum.Models.User;
  12. using Microsoft.AspNetCore.Identity;
  13. using Microsoft.AspNetCore.Mvc;
  14. using Microsoft.AspNetCore.Mvc.RazorPages;
  15. using Microsoft.Extensions.Logging;
  16. namespace bitforum.Areas.Identity.Pages.Account.Manage
  17. {
  18. public class EnableAuthenticatorModel : PageModel
  19. {
  20. private readonly UserManager<ApplicationUser> _userManager;
  21. private readonly ILogger<EnableAuthenticatorModel> _logger;
  22. private readonly UrlEncoder _urlEncoder;
  23. private const string AuthenticatorUriFormat = "otpauth://totp/{0}:{1}?secret={2}&issuer={0}&digits=6";
  24. public EnableAuthenticatorModel(
  25. UserManager<ApplicationUser> userManager,
  26. ILogger<EnableAuthenticatorModel> logger,
  27. UrlEncoder urlEncoder)
  28. {
  29. _userManager = userManager;
  30. _logger = logger;
  31. _urlEncoder = urlEncoder;
  32. }
  33. /// <summary>
  34. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  35. /// directly from your code. This API may change or be removed in future releases.
  36. /// </summary>
  37. public string SharedKey { get; set; }
  38. /// <summary>
  39. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  40. /// directly from your code. This API may change or be removed in future releases.
  41. /// </summary>
  42. public string AuthenticatorUri { get; set; }
  43. /// <summary>
  44. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  45. /// directly from your code. This API may change or be removed in future releases.
  46. /// </summary>
  47. [TempData]
  48. public string[] RecoveryCodes { get; set; }
  49. /// <summary>
  50. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  51. /// directly from your code. This API may change or be removed in future releases.
  52. /// </summary>
  53. [TempData]
  54. public string StatusMessage { get; set; }
  55. /// <summary>
  56. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  57. /// directly from your code. This API may change or be removed in future releases.
  58. /// </summary>
  59. [BindProperty]
  60. public InputModel Input { get; set; }
  61. /// <summary>
  62. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  63. /// directly from your code. This API may change or be removed in future releases.
  64. /// </summary>
  65. public class InputModel
  66. {
  67. /// <summary>
  68. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  69. /// directly from your code. This API may change or be removed in future releases.
  70. /// </summary>
  71. [Required]
  72. [StringLength(7, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
  73. [DataType(DataType.Text)]
  74. [Display(Name = "Verification Code")]
  75. public string Code { get; set; }
  76. }
  77. public async Task<IActionResult> OnGetAsync()
  78. {
  79. var user = await _userManager.GetUserAsync(User);
  80. if (user == null)
  81. {
  82. return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
  83. }
  84. await LoadSharedKeyAndQrCodeUriAsync(user);
  85. return Page();
  86. }
  87. public async Task<IActionResult> OnPostAsync()
  88. {
  89. var user = await _userManager.GetUserAsync(User);
  90. if (user == null)
  91. {
  92. return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
  93. }
  94. if (!ModelState.IsValid)
  95. {
  96. await LoadSharedKeyAndQrCodeUriAsync(user);
  97. return Page();
  98. }
  99. // Strip spaces and hyphens
  100. var verificationCode = Input.Code.Replace(" ", string.Empty).Replace("-", string.Empty);
  101. var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync(
  102. user, _userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode);
  103. if (!is2faTokenValid)
  104. {
  105. ModelState.AddModelError("Input.Code", "Verification code is invalid.");
  106. await LoadSharedKeyAndQrCodeUriAsync(user);
  107. return Page();
  108. }
  109. await _userManager.SetTwoFactorEnabledAsync(user, true);
  110. var userId = await _userManager.GetUserIdAsync(user);
  111. _logger.LogInformation("User with ID '{UserId}' has enabled 2FA with an authenticator app.", userId);
  112. StatusMessage = "Your authenticator app has been verified.";
  113. if (await _userManager.CountRecoveryCodesAsync(user) == 0)
  114. {
  115. var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
  116. RecoveryCodes = recoveryCodes.ToArray();
  117. return RedirectToPage("./ShowRecoveryCodes");
  118. }
  119. else
  120. {
  121. return RedirectToPage("./TwoFactorAuthentication");
  122. }
  123. }
  124. private async Task LoadSharedKeyAndQrCodeUriAsync(ApplicationUser user)
  125. {
  126. // Load the authenticator key & QR code URI to display on the form
  127. var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
  128. if (string.IsNullOrEmpty(unformattedKey))
  129. {
  130. await _userManager.ResetAuthenticatorKeyAsync(user);
  131. unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
  132. }
  133. SharedKey = FormatKey(unformattedKey);
  134. var email = await _userManager.GetEmailAsync(user);
  135. AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey);
  136. }
  137. private string FormatKey(string unformattedKey)
  138. {
  139. var result = new StringBuilder();
  140. int currentPosition = 0;
  141. while (currentPosition + 4 < unformattedKey.Length)
  142. {
  143. result.Append(unformattedKey.AsSpan(currentPosition, 4)).Append(' ');
  144. currentPosition += 4;
  145. }
  146. if (currentPosition < unformattedKey.Length)
  147. {
  148. result.Append(unformattedKey.AsSpan(currentPosition));
  149. }
  150. return result.ToString().ToLowerInvariant();
  151. }
  152. private string GenerateQrCodeUri(string email, string unformattedKey)
  153. {
  154. return string.Format(
  155. CultureInfo.InvariantCulture,
  156. AuthenticatorUriFormat,
  157. _urlEncoder.Encode("Microsoft.AspNetCore.Identity.UI"),
  158. _urlEncoder.Encode(email),
  159. unformattedKey);
  160. }
  161. }
  162. }