ExternalLogin.cshtml.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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.Security.Claims;
  7. using System.Text;
  8. using System.Text.Encodings.Web;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using Microsoft.AspNetCore.Authorization;
  12. using Microsoft.Extensions.Options;
  13. using Microsoft.AspNetCore.Identity;
  14. using Microsoft.AspNetCore.Identity.UI.Services;
  15. using Microsoft.AspNetCore.Mvc;
  16. using Microsoft.AspNetCore.Mvc.RazorPages;
  17. using Microsoft.AspNetCore.WebUtilities;
  18. using Microsoft.Extensions.Logging;
  19. using bitforum.Models.User;
  20. namespace bitforum.Areas.Identity.Pages.Account
  21. {
  22. [AllowAnonymous]
  23. public class ExternalLoginModel : PageModel
  24. {
  25. private readonly SignInManager<ApplicationUser> _signInManager;
  26. private readonly UserManager<ApplicationUser> _userManager;
  27. private readonly IUserStore<ApplicationUser> _userStore;
  28. private readonly IUserEmailStore<ApplicationUser> _emailStore;
  29. private readonly IEmailSender _emailSender;
  30. private readonly ILogger<ExternalLoginModel> _logger;
  31. public ExternalLoginModel(
  32. SignInManager<ApplicationUser> signInManager,
  33. UserManager<ApplicationUser> userManager,
  34. IUserStore<ApplicationUser> userStore,
  35. ILogger<ExternalLoginModel> logger,
  36. IEmailSender emailSender)
  37. {
  38. _signInManager = signInManager;
  39. _userManager = userManager;
  40. _userStore = userStore;
  41. _emailStore = GetEmailStore();
  42. _logger = logger;
  43. _emailSender = emailSender;
  44. }
  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. [BindProperty]
  50. public InputModel Input { get; set; }
  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. public string ProviderDisplayName { get; set; }
  56. /// <summary>
  57. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  58. /// directly from your code. This API may change or be removed in future releases.
  59. /// </summary>
  60. public string ReturnUrl { 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. [TempData]
  66. public string ErrorMessage { get; set; }
  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. public class InputModel
  72. {
  73. /// <summary>
  74. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  75. /// directly from your code. This API may change or be removed in future releases.
  76. /// </summary>
  77. [Required]
  78. [EmailAddress]
  79. public string Email { get; set; }
  80. }
  81. public IActionResult OnGet() => RedirectToPage("./Login");
  82. public IActionResult OnPost(string provider, string returnUrl = null)
  83. {
  84. // Request a redirect to the external login provider.
  85. var redirectUrl = Url.Page("./ExternalLogin", pageHandler: "Callback", values: new { returnUrl });
  86. var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
  87. return new ChallengeResult(provider, properties);
  88. }
  89. public async Task<IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null)
  90. {
  91. returnUrl = returnUrl ?? Url.Content("~/");
  92. if (remoteError != null)
  93. {
  94. ErrorMessage = $"Error from external provider: {remoteError}";
  95. return RedirectToPage("./Login", new { ReturnUrl = returnUrl });
  96. }
  97. var info = await _signInManager.GetExternalLoginInfoAsync();
  98. if (info == null)
  99. {
  100. ErrorMessage = "Error loading external login information.";
  101. return RedirectToPage("./Login", new { ReturnUrl = returnUrl });
  102. }
  103. // Sign in the user with this external login provider if the user already has a login.
  104. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
  105. if (result.Succeeded)
  106. {
  107. _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider);
  108. return LocalRedirect(returnUrl);
  109. }
  110. if (result.IsLockedOut)
  111. {
  112. return RedirectToPage("./Lockout");
  113. }
  114. else
  115. {
  116. // If the user does not have an account, then ask the user to create an account.
  117. ReturnUrl = returnUrl;
  118. ProviderDisplayName = info.ProviderDisplayName;
  119. if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email))
  120. {
  121. Input = new InputModel
  122. {
  123. Email = info.Principal.FindFirstValue(ClaimTypes.Email)
  124. };
  125. }
  126. return Page();
  127. }
  128. }
  129. public async Task<IActionResult> OnPostConfirmationAsync(string returnUrl = null)
  130. {
  131. returnUrl = returnUrl ?? Url.Content("~/");
  132. // Get the information about the user from the external login provider
  133. var info = await _signInManager.GetExternalLoginInfoAsync();
  134. if (info == null)
  135. {
  136. ErrorMessage = "Error loading external login information during confirmation.";
  137. return RedirectToPage("./Login", new { ReturnUrl = returnUrl });
  138. }
  139. if (ModelState.IsValid)
  140. {
  141. var user = CreateUser();
  142. await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);
  143. await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);
  144. var result = await _userManager.CreateAsync(user);
  145. if (result.Succeeded)
  146. {
  147. result = await _userManager.AddLoginAsync(user, info);
  148. if (result.Succeeded)
  149. {
  150. _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
  151. var userId = await _userManager.GetUserIdAsync(user);
  152. var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
  153. code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
  154. var callbackUrl = Url.Page(
  155. "/Account/ConfirmEmail",
  156. pageHandler: null,
  157. values: new { area = "Identity", userId = userId, code = code },
  158. protocol: Request.Scheme);
  159. await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
  160. $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
  161. // If account confirmation is required, we need to show the link if we don't have a real email sender
  162. if (_userManager.Options.SignIn.RequireConfirmedAccount)
  163. {
  164. return RedirectToPage("./RegisterConfirmation", new { Email = Input.Email });
  165. }
  166. await _signInManager.SignInAsync(user, isPersistent: false, info.LoginProvider);
  167. return LocalRedirect(returnUrl);
  168. }
  169. }
  170. foreach (var error in result.Errors)
  171. {
  172. ModelState.AddModelError(string.Empty, error.Description);
  173. }
  174. }
  175. ProviderDisplayName = info.ProviderDisplayName;
  176. ReturnUrl = returnUrl;
  177. return Page();
  178. }
  179. private ApplicationUser CreateUser()
  180. {
  181. try
  182. {
  183. return Activator.CreateInstance<ApplicationUser>();
  184. }
  185. catch
  186. {
  187. throw new InvalidOperationException($"Can't create an instance of '{nameof(ApplicationUser)}'. " +
  188. $"Ensure that '{nameof(ApplicationUser)}' is not an abstract class and has a parameterless constructor, or alternatively " +
  189. $"override the external login page in /Areas/Identity/Pages/Account/ExternalLogin.cshtml");
  190. }
  191. }
  192. private IUserEmailStore<ApplicationUser> GetEmailStore()
  193. {
  194. if (!_userManager.SupportsUserEmail)
  195. {
  196. throw new NotSupportedException("The default UI requires a user store with email support.");
  197. }
  198. return (IUserEmailStore<ApplicationUser>)_userStore;
  199. }
  200. }
  201. }