Beispiel #1
0
        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());
            }
        }
Beispiel #2
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null)
        {
            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)
            {
                _logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
                return(RedirectToLocal(returnUrl));
            }
            if (result.RequiresTwoFactor)
            {
                return(RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl }));
            }
            if (result.IsLockedOut)
            {
                return(View("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.ExternalPrincipal.FindFirstValue(ClaimTypes.Email);
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    Email = email
                }));
            }
        }
        public async Task <IActionResult> SignInCompleteAsync()
        {
            string returnUrl = "/";
            //returnUrl = returnUrl ?? "/";
            var info = await SignInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                // El login no es válido o no se ha completado
                return(BadRequest());
            }

            //var userid = info.Principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
            //var name = info.Principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name);

            //var identityAtDb = await UserManager.FindByLoginAsync(info.LoginProvider, info.ProviderKey);
            //if (identityAtDb == null)
            //{
            //    identityAtDb = await UserManager.FindByEmailAsync(email);
            //    if(identityAtDb == null)
            //    {
            //        identityAtDb = new MyUser();
            //        identityAtDb.Email = email;
            //    }
            //}
            //var userAtIdentity = await UserManager.FindByEmailAsync


            var result = await SignInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (result.Succeeded)
            {
                return(Ok());
            }
            if (result.IsLockedOut)
            {
                return(Forbid());
            }
            else
            {
                // La idea es: si el usuario no tiene una cuenta creada y enlazada con el proveedor (hubiera pasado por result.Succeeded)
                // exijimos (si aplica) que se cree una cuenta.
                // Podemos coger los Claims que nos provee el servicio externo.
                var email = info.Principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
                if (string.IsNullOrWhiteSpace(email))
                {
                    return(SignOut());
                }

                var identityUser = new MyUser();
                await UserStore.SetUserNameAsync(identityUser, email, System.Threading.CancellationToken.None);

                await EmailStore.SetEmailAsync(identityUser, email, System.Threading.CancellationToken.None);

                var createResult = await UserManager.CreateAsync(identityUser);

                if (createResult.Succeeded)
                {
                    await SignInManager.SignInAsync(identityUser, isPersistent : false);

                    return(Redirect("/"));
                }
                else
                {
                    foreach (var error in createResult.Errors)
                    {
                        ModelState.AddModelError(error.Code, error.Description);
                    }
                    return(BadRequest(ModelState));
                }
            }
        }