EnableAuthenticator.cshtml.cs 7.3 KB

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