LoginWith2fa.cshtml.cs 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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.Threading.Tasks;
  7. using Microsoft.AspNetCore.Authorization;
  8. using Microsoft.AspNetCore.Mvc;
  9. using Microsoft.AspNetCore.Mvc.RazorPages;
  10. using Microsoft.Extensions.Logging;
  11. using Microsoft.AspNetCore.Identity;
  12. using Microsoft.Extensions.Logging;
  13. namespace bitforum.Areas.Identity.Pages.Account
  14. {
  15. public class LoginWith2faModel : PageModel
  16. {
  17. private readonly SignInManager<IdentityUser> _signInManager;
  18. private readonly UserManager<IdentityUser> _userManager;
  19. private readonly ILogger<LoginWith2faModel> _logger;
  20. public LoginWith2faModel(
  21. SignInManager<IdentityUser> signInManager,
  22. UserManager<IdentityUser> userManager,
  23. ILogger<LoginWith2faModel> logger)
  24. {
  25. _signInManager = signInManager;
  26. _userManager = userManager;
  27. _logger = logger;
  28. }
  29. /// <summary>
  30. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  31. /// directly from your code. This API may change or be removed in future releases.
  32. /// </summary>
  33. [BindProperty]
  34. public InputModel Input { get; set; }
  35. /// <summary>
  36. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  37. /// directly from your code. This API may change or be removed in future releases.
  38. /// </summary>
  39. public bool RememberMe { get; set; }
  40. /// <summary>
  41. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  42. /// directly from your code. This API may change or be removed in future releases.
  43. /// </summary>
  44. public string ReturnUrl { get; set; }
  45. /// <summary>
  46. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  47. /// directly from your code. This API may change or be removed in future releases.
  48. /// </summary>
  49. public class InputModel
  50. {
  51. /// <summary>
  52. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  53. /// directly from your code. This API may change or be removed in future releases.
  54. /// </summary>
  55. [Required]
  56. [StringLength(7, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
  57. [DataType(DataType.Text)]
  58. [Display(Name = "Authenticator code")]
  59. public string TwoFactorCode { 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. [Display(Name = "Remember this machine")]
  65. public bool RememberMachine { get; set; }
  66. }
  67. public async Task<IActionResult> OnGetAsync(bool rememberMe, string returnUrl = null)
  68. {
  69. // Ensure the user has gone through the username & password screen first
  70. var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
  71. if (user == null)
  72. {
  73. throw new InvalidOperationException($"Unable to load two-factor authentication user.");
  74. }
  75. ReturnUrl = returnUrl;
  76. RememberMe = rememberMe;
  77. return Page();
  78. }
  79. public async Task<IActionResult> OnPostAsync(bool rememberMe, string returnUrl = null)
  80. {
  81. if (!ModelState.IsValid)
  82. {
  83. return Page();
  84. }
  85. returnUrl = returnUrl ?? Url.Content("~/");
  86. var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
  87. if (user == null)
  88. {
  89. throw new InvalidOperationException($"Unable to load two-factor authentication user.");
  90. }
  91. var authenticatorCode = Input.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty);
  92. var result = await _signInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, rememberMe, Input.RememberMachine);
  93. var userId = await _userManager.GetUserIdAsync(user);
  94. if (result.Succeeded)
  95. {
  96. _logger.LogInformation("User with ID '{UserId}' logged in with 2fa.", user.Id);
  97. return LocalRedirect(returnUrl);
  98. }
  99. else if (result.IsLockedOut)
  100. {
  101. _logger.LogWarning("User with ID '{UserId}' account locked out.", user.Id);
  102. return RedirectToPage("./Lockout");
  103. }
  104. else
  105. {
  106. _logger.LogWarning("Invalid authenticator code entered for user with ID '{UserId}'.", user.Id);
  107. ModelState.AddModelError(string.Empty, "Invalid authenticator code.");
  108. return Page();
  109. }
  110. }
  111. }
  112. }