public async Task <ActionResult> LinkLoginCallback() { var user = await GetCurrentUserAsync(); if (user == null) { return(View("Error")); } var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user)); if (info == null) { return(RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error })); } var result = await _userManager.AddLoginAsync(user, info); var message = ManageMessageId.Error; if (result.Succeeded) { message = ManageMessageId.AddLoginSuccess; // Clear the existing external cookie to ensure a clean login process await HttpContext.Authentication.SignOutAsync(_externalCookieScheme); } return(RedirectToAction(nameof(ManageLogins), new { Message = message })); }
public async Task <IActionResult> LinkLoginCallback() { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var info = await _signInManager.GetExternalLoginInfoAsync(user.Id.ToString()); if (info == null) { throw new ApplicationException($"Unexpected error occurred loading external login info for user with ID '{user.Id}'."); } var result = await _userManager.AddLoginAsync(user, info); if (!result.Succeeded) { throw new ApplicationException($"Unexpected error occurred adding external login for user with ID '{user.Id}'."); } // Clear the existing external cookie to ensure a clean login process await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); StatusMessage = "The external login was added."; return(RedirectToAction(nameof(ExternalLogins))); }
public async Task <IActionResult> OnGetLinkLoginCallbackAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user)); if (info == null) { throw new InvalidOperationException($"Unexpected error occurred loading external login info for user with ID '{user.Id}'."); } var result = await _userManager.AddLoginAsync(user, info); if (!result.Succeeded) { StatusMessage = "The external login was not added. External logins can only be associated with one account."; return(RedirectToPage()); } // Clear the existing external cookie to ensure a clean login process await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); StatusMessage = "The external login was added."; return(RedirectToPage()); }
public async Task <IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (remoteError != null) { ErrorMessage = $"Error from external provider: {remoteError}"; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information."; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true); if (result.Succeeded) { _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider); return(LocalRedirect(returnUrl)); } if (result.IsLockedOut) { return(RedirectToPage("./Lockout")); } else { // If the user does not have an account, then ask the user to create an account. ReturnUrl = returnUrl; LoginProvider = info.LoginProvider; if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email)) { Input = new InputModel { Email = info.Principal.FindFirstValue(ClaimTypes.Email) }; } return(Page()); } }
public async Task <IActionResult> loginexternalcallback(string returnUrl = null, string remoteError = null) { if (remoteError != null) { _logger.LogError($"Error from external provider: {remoteError}"); return(RedirectToAction(nameof(login))); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { _logger.LogDebug($"GetExternalLoginInfoAsync() returned null"); return(RedirectToAction(nameof(login))); } _logger.LogInformation($"Callback from LoginProvider={info.LoginProvider} ProviderKey={info.ProviderKey} ProviderDisplayName={info.ProviderDisplayName}"); foreach (var claim in info.Principal.Claims) { _logger.LogDebug($"Claim: Type={claim.Type} Value={claim.Value} Issuer={claim.Issuer}"); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true); if (result.Succeeded) { _logger.LogInformation("Login succeeded; user already has login"); // TODO: fetch image return(RedirectToLocal(returnUrl)); } if (result.IsLockedOut) { // TODO: handle locked out case _logger.LogInformation("User is locked out"); return(RedirectToAction(nameof(login))); } else { _logger.LogInformation("Need to create login for user; redirecting"); return(RedirectToAction(nameof(registerexternal))); } }
public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null) { if (remoteError != null) { ModelState.AddModelError(string.Empty, _localizer["ErrorExternalProvider", remoteError]); return(View(nameof(Login))); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return(RedirectToAction(nameof(Login))); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false); if (result.Succeeded) { return(RedirectToLocal(returnUrl)); } if (result.RequiresTwoFactor) { return(RedirectToAction(nameof(LoginWith2fa), new { ReturnUrl = returnUrl })); } if (result.IsLockedOut) { return(View("Lockout")); } // If the user does not have an account, then ask the user to create an account. ViewData["ReturnUrl"] = returnUrl; ViewData["LoginProvider"] = info.LoginProvider; var email = info.Principal.FindFirstValue(ClaimTypes.Email); var userName = info.Principal.Identity.Name; return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email, UserName = userName })); }
public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null) { if (remoteError != null) { ErrorMessage = $"Error from external provider: {remoteError}"; return(RedirectToAction(nameof(Login))); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return(RedirectToAction(nameof(Login))); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true); if (result.Succeeded) { _logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider); return(RedirectToLocal(returnUrl)); } if (result.IsLockedOut) { return(RedirectToAction(nameof(Lockout))); } else { // If the user does not have an account, then ask the user to create an account. ViewData["ReturnUrl"] = returnUrl; ViewData["LoginProvider"] = info.LoginProvider; var email = info.Principal.FindFirstValue(ClaimTypes.Email); return(View("ExternalLogin", new ExternalLoginViewModel { Email = email })); } }
public async Task <IActionResult> OnGetLinkLoginCallbackAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user)); if (info == null) { throw new InvalidOperationException($"Unexpected error occurred loading external login info for user with ID '{user.Id}'."); } var result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { // add the email as claim when it is different than the user's email var externalEmail = info.Principal.FindFirst(ClaimTypes.Email)?.Value?.ToLower(); var userEmail = await _userManager.GetEmailAsync(user); if (!string.IsNullOrWhiteSpace(externalEmail) && _userManager.NormalizeEmail(userEmail) != _userManager.NormalizeEmail(externalEmail)) { var currentClaims = await _userManager.GetClaimsAsync(user); if (!currentClaims.Any(c => c.Type == ClaimTypes.Email && c.Value == externalEmail)) { await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Email, externalEmail)); // update claims for cookie await _signInManager.RefreshSignInAsync(user); } } } else //if (!result.Succeeded) { StatusMessage = "The external login was not added. External logins can only be associated with one account."; return(RedirectToPage()); } // Clear the existing external cookie to ensure a clean login process await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); StatusMessage = "The external login was added."; return(RedirectToPage()); }
public async Task <ExternalLoginInfo> GetExternalLoginInfo() { return(await _signInManager.GetExternalLoginInfoAsync()); }
public async Task <IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null) { returnUrl ??= Url.Content("~/"); if (remoteError != null) { ErrorMessage = $"Error from external provider: {remoteError}"; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information."; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, false, true); if (result.Succeeded) { _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider); return(LocalRedirect(returnUrl)); } if (result.IsLockedOut) { return(RedirectToPage("./Lockout")); } // If the user does not have an account, then create an account automatically. ReturnUrl = returnUrl; LoginProvider = info.LoginProvider; if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email)) { var createResult = await _externalAccountHelper.CreateUser(info); if (createResult.Succeeded) { var principal = info.Principal; Input = new InputModel { Email = principal.FindFirstValue(ClaimTypes.Email), PhoneNumber = principal.FindFirstValue(ClaimTypes.MobilePhone) ?? principal.FindFirstValue(ClaimTypes.HomePhone) ?? principal.FindFirstValue(ClaimTypes.OtherPhone), GivenName = principal.FindFirstValue(ClaimTypes.GivenName), FamilyName = principal.FindFirstValue(ClaimTypes.Surname) }; } else { foreach (var error in createResult.Errors) { if (error.Code == "DuplicateUserName") { ShowVerifyEmailLink = true; // skip to avoid error message for username AND email continue; } ModelState.AddModelError(string.Empty, error.Description); } } } return(Page()); }
public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null) { if (remoteError != null) { ErrorMessage = $"Error from external provider: {remoteError}"; return(RedirectToAction(nameof(Login))); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return(RedirectToAction(nameof(Login))); } //Verifica se usuário já está cadastrado na base de dados da aplicação var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true); if (result.Succeeded) { _logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider); return(RedirectToAction(nameof(EstudanteController.Roll), "Estudante")); } if (result.IsLockedOut) { return(RedirectToAction(nameof(Lockout))); } // If the user does not have an account, then ask the user to create an account. ViewData["ReturnUrl"] = returnUrl; ViewData["LoginProvider"] = info.LoginProvider; var email = info.Principal.FindFirstValue(ClaimTypes.Email); var phone = info.Principal.FindFirstValue(ClaimTypes.MobilePhone); var name = info.Principal.FindFirstValue(ClaimTypes.GivenName); var surname = info.Principal.FindFirstValue(ClaimTypes.Surname); var birthday = info.Principal.FindFirstValue(ClaimTypes.DateOfBirth); var gender = info.Principal.FindFirstValue(ClaimTypes.Gender); var location = info.Principal.FindFirstValue(ClaimTypes.Locality); var identifier = info.Principal.FindFirstValue(ClaimTypes.NameIdentifier); var picture = $"https://graph.facebook.com/{identifier}/picture?type=large"; var externalLoginViewModel = new ExternalLoginViewModel { GeneroId = gender == "male" ? 1 : gender == "female" ? 2 : 1, Nome = name, Sobrenome = surname, DataNascimento = DateTime.Parse(birthday, new CultureInfo("en-US")), Email = email, PhoneNumber = phone, Localizacao = location, CaminhoFoto = picture, Cursos = new SelectList(_cursoAppService.GetAll().OrderBy(x => x.Nome), "Id", "Nome"), OrientacoesPoliticas = new SelectList(_estudanteAppService.ListarOrientacoesPoliticas(), "Id", "Nome"), TiposDeConsumoBebida = new SelectList(_estudanteAppService.ListarTiposDeConsumoBebida(), "Id", "Nome"), TiposDeAtracao = _estudanteAppService.ListarTiposDeAtracao().Select(x => new CheckBoxListItem { Id = x.Id, Text = x.Nome }).ToArray(), GenerosInteresse = new[] { new CheckBoxListItem { Id = 1, Text = "Homens" }, new CheckBoxListItem { Id = 2, Text = "Mulheres" }, } }; return(View(nameof(ExternalLogin), externalLoginViewModel)); }