示例#1
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            LoginViewModel loginViewModel = new LoginViewModel
            {
                ReturnUrl = returnUrl,

                // A list of all external login providers configured
                ExternalLogins = (await signInManager.GetExternalAuthenticationSchemesAsync()).ToList()
            };

            if (remoteError != null)
            {
                ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");

                return(View("Login", loginViewModel));
            }

            var info = await signInManager.GetExternalLoginInfoAsync();

            // When we have not receive any login information from external provider
            if (info == null)
            {
                ModelState.AddModelError(string.Empty, "Error loading external login information");
                return(View("Login", loginViewModel));
            }

            // Retrieve the email value from the object received from the external login provider
            var email = info.Principal.FindFirstValue(ClaimTypes.Email);

            ApplicationUser user = null;

            if (email != null)
            {
                user = await userManager.FindByEmailAsync(email);

                if (user != null && !user.EmailConfirmed)
                {
                    // Generate an token for a specified user to confirmed their email
                    string token = await userManager.GenerateEmailConfirmationTokenAsync(user);

                    // This link is send to user to his email and when he clicks on it, it confirm his account email
                    string confirmationLink = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, token = token }, Request.Scheme);

                    // For now log the link and copy it to the browser
                    logger.Log(LogLevel.Warning, confirmationLink);

                    await this.emailSender.SendEmailAsync(user.Email, "Email Confirmation", confirmationLink);

                    ModelState.AddModelError(string.Empty, "Email not confirmed yet, please confirm your email");
                    return(View("Login", loginViewModel));
                }
            }

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

            if (signInResult.Succeeded)
            {
                return(LocalRedirect(returnUrl));
            }
            else
            {
                if (email != null)
                {
                    // This occurs when we cannot find a user in the local user account so we have to firts create that user in our local database
                    if (user == null)
                    {
                        user = new ApplicationUser
                        {
                            UserName = info.Principal.FindFirstValue(ClaimTypes.Email),
                            Email    = info.Principal.FindFirstValue(ClaimTypes.Email)
                        };

                        // This create a new record in AspNetUsers table
                        await userManager.CreateAsync(user);

                        // Generate an token for a specified user to confirmed their email
                        string token = await userManager.GenerateEmailConfirmationTokenAsync(user);

                        // This link is send to user to his email and when he clicks on it, it confirm his account email
                        string confirmationLink = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, token = token }, Request.Scheme);

                        // For now log the link and copy it to the browser
                        logger.Log(LogLevel.Warning, confirmationLink);

                        // Generate an token for a specified user to confirmed their email
                        token = await userManager.GenerateEmailConfirmationTokenAsync(user);

                        // This link is send to user to his email and when he clicks on it, it confirm his account email
                        confirmationLink = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, token = token }, Request.Scheme);

                        // For now log the link and copy it to the browser
                        logger.Log(LogLevel.Warning, confirmationLink);

                        await this.emailSender.SendEmailAsync(user.Email, "Email Confirmation", confirmationLink);

                        ViewBag.ErrorTitle   = "Registration Successful";
                        ViewBag.ErrorMessage = "Before you can login, please confirm your email, by clicking on the confirmation link we have email to you";
                        return(View("Error"));
                    }

                    // Add the user in the AspNetUserLogins table
                    await userManager.AddLoginAsync(user, info);

                    await signInManager.SignInAsync(user, isPersistent : false);

                    return(LocalRedirect(returnUrl));
                }

                // This is when the login provider does not provide email address of the user
                ViewBag.ErrorTitle   = $"Email claim not received from: {info.LoginProvider}";
                ViewBag.ErrorMessage = "Please contact support on [email protected]";
                return(View("Error"));
            }
        }
        ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            LoginViewModel loginViewModel = new LoginViewModel
            {
                ReturnUrl      = returnUrl,
                ExternalLogins =
                    (await signInManager.GetExternalAuthenticationSchemesAsync()).ToList()
            };

            if (remoteError != null)
            {
                ModelState
                .AddModelError(string.Empty, $"Error from external provider: {remoteError}");

                return(View("Login", loginViewModel));
            }

            // Get the login information about the user from the external login provider
            var info = await signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ModelState
                .AddModelError(string.Empty, "Error loading external login information.");

                return(View("Login", loginViewModel));
            }

            // If the user already has a login (i.e if there is a record in AspNetUserLogins
            // table) then sign-in the user with this external login provider
            var signInResult = await signInManager.ExternalLoginSignInAsync(info.LoginProvider,
                                                                            info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (signInResult.Succeeded)
            {
                return(LocalRedirect(returnUrl));
            }
            // If there is no record in AspNetUserLogins table, the user may not have
            // a local account
            else
            {
                // Get the email claim value
                var email = info.Principal.FindFirstValue(ClaimTypes.Email);

                if (email != null)
                {
                    // Create a new user without password if we do not have a user already
                    var user = await userManager.FindByEmailAsync(email);

                    if (user == null)
                    {
                        user = new ApplicationUser
                        {
                            UserName = info.Principal.FindFirstValue(ClaimTypes.Email),
                            Email    = info.Principal.FindFirstValue(ClaimTypes.Email)
                        };

                        await userManager.CreateAsync(user);
                    }

                    // Add a login (i.e insert a row for the user in AspNetUserLogins table)
                    await userManager.AddLoginAsync(user, info);

                    await signInManager.SignInAsync(user, isPersistent : false);

                    return(LocalRedirect(returnUrl));
                }

                // If we cannot find the user email we cannot continue
                ViewBag.ErrorTitle   = $"Email claim not received from: {info.LoginProvider}";
                ViewBag.ErrorMessage = "Please contact support on [email protected]";

                return(View("Error"));
            }
        }
            ExternalLoginCallBack(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            LoginViewModel loginViewModel = new LoginViewModel
            {
                ReturnUrl = returnUrl,
                ExternalLogins = (await signInManager.GetExternalAuthenticationSchemesAsync()).ToList()
            };

            if(remoteError != null)
            {
                ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");

                return View("login", loginViewModel);
            }

            var info = await signInManager.GetExternalLoginInfoAsync();
            if (info == null)
            {
                ModelState.AddModelError(string.Empty, "Error loading external login information.");

                return View("Login", loginViewModel);
            }

            var email = info.Principal.FindFirstValue(ClaimTypes.Email);
            ApplicationUser user = null;

            if (email != null)
            {
                user = await userManager.FindByEmailAsync(email);

                if (user != null && !user.EmailConfirmed)
                {
                    ModelState.AddModelError(string.Empty, "Email not confirmed yet");
                    return View("Login", loginViewModel);
                }
            }

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

            if (signInResult.Succeeded)
            {
                return LocalRedirect(returnUrl);
            }
            else
            {               

                if(email != null)
                {
                    if(user == null)
                    {
                        user = new ApplicationUser
                        {
                            UserName = info.Principal.FindFirstValue(ClaimTypes.Email),
                            Email = info.Principal.FindFirstValue(ClaimTypes.Email)
                        };

                        await userManager.CreateAsync(user);

                        var token = await userManager.GenerateEmailConfirmationTokenAsync(user);

                        var confirmationLink = Url.Action("ConfirmEmail", "Account",
                            new { userId = user.Id, token = token }, Request.Scheme);

                        logger.Log(LogLevel.Warning, confirmationLink);

                        ViewBag.ErrorTitle = "Registration successful";
                        ViewBag.ErrorMessage = "Before you can login, please confirm your " +
                            "email, by clicking on the confirmation link we have emailed you";
                        return View("Error");
                    }

                    await userManager.AddLoginAsync(user, info);
                    await signInManager.SignInAsync(user, isPersistent: false);

                    return LocalRedirect(returnUrl);
                }

                ViewBag.ErrorTitle = $"Email claim no receive from:{info.LoginProvider}";
                ViewBag.ErrorMessage = "Please contact support on [email protected]";
                return View("Error");
            }
        }
示例#4
0
        ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            LoginViewModel loginViewModel = new LoginViewModel
            {
                ReturnUrl      = returnUrl,
                ExternalLogins = (await signInManager.GetExternalAuthenticationSchemesAsync()).ToList()
            };

            if (remoteError != null)
            {
                ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");

                return(View("Login", loginViewModel));
            }

            var info = await signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ModelState.AddModelError(string.Empty, "Error loading external login information");

                return(View("Login", loginViewModel));
            }

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

            if (signInResult.Succeeded)
            {
                return(LocalRedirect(returnUrl));
            }
            else
            {
                var email = info.Principal.FindFirstValue(ClaimTypes.Email);

                if (email != null)
                {
                    var user = await userManager.FindByEmailAsync(email);

                    if (user == null)
                    {
                        user = new ApplicationUser
                        {
                            UserName = info.Principal.FindFirstValue(ClaimTypes.Email),
                            Email    = info.Principal.FindFirstValue(ClaimTypes.Email)
                        };

                        await userManager.CreateAsync(user);
                    }

                    await userManager.AddLoginAsync(user, info);

                    await signInManager.SignInAsync(user, isPersistent : false);

                    return(LocalRedirect(returnUrl));
                }

                ViewBag.ErrorTitle   = $"Email claim not received from: {info.LoginProvider}";
                ViewBag.ErrorMessage = "Please contact support on [email protected]";

                return(View("Error"));
            }
        }
示例#5
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            LoginViewModel loginViewModel = new LoginViewModel
            {
                ReturnUrl      = returnUrl,
                ExternalLogins =
                    (await signInManager.GetExternalAuthenticationSchemesAsync()).ToList()
            };

            if (remoteError != null)
            {
                ModelState
                .AddModelError(string.Empty, $"Error from external provider: {remoteError}");

                return(View("Login", loginViewModel));
            }

            // Get the login information about the user from the external login provider
            var info = await signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ModelState
                .AddModelError(string.Empty, "Error loading external login information.");

                return(View("Login", loginViewModel));
            }

            //  Get the email claim value
            //Get the email claim from external login provider(Google, Facebook etc)
            var email = info.Principal.FindFirstValue(ClaimTypes.Email);

            // Create a new user
            ApplicationUser user = null;



            if (email != null)
            {
                // Find the user
                user = await userManager.FindByEmailAsync(email);

                // If email is not confirmed, display login view with validation error
                if (user != null && !user.EmailConfirmed)
                {
                    ModelState.AddModelError(string.Empty, "Email Not Confirmed Yet");
                    return(View("login", loginViewModel));
                }
            }



            // If the user already has a login (i.e if there is a record in AspNetUserLogins
            // table) then sign-in the user with this external login provider
            var signInResult = await signInManager.ExternalLoginSignInAsync(info.LoginProvider,
                                                                            info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (signInResult.Succeeded)
            {
                return(LocalRedirect(returnUrl));
            }
            // If there is no record in AspNetUserLogins table, the user may not have
            // a local account
            else
            {
                if (email != null)
                {
                    // user without password if we do not have a user already

                    // user = await userManager.FindByEmailAsync(email); //delelte becuase it is diclaration in the above

                    if (user == null)
                    {
                        user = new ApplicationUser
                        {
                            UserName = info.Principal.FindFirstValue(ClaimTypes.Email),
                            Email    = info.Principal.FindFirstValue(ClaimTypes.Email)
                        };

                        await userManager.CreateAsync(user);

                        // After a local user account is created, generate and log the
                        // email confirmation link

                        // Generate the email confirmation token
                        var token = await userManager.GenerateEmailConfirmationTokenAsync(user);

                        //Generate Email Confirmation Link
                        var confirmationLink = Url.Action("ConfirmEmail", "Account",
                                                          new { userId = user.Id, token = token }, Request.Scheme);

                        // save the token in log file
                        logger.Log(LogLevel.Warning, confirmationLink);

                        ViewBag.ErrorTitle   = "Registration Successful ";
                        ViewBag.ErrorMessage = "Before you can login, please confirm you email," +
                                               " By clicking on the confirmation link we have emailed you";
                        return(View("Error"));
                    }

                    // Add a login (i.e insert a row for the user in AspNetUserLogins table)
                    await userManager.AddLoginAsync(user, info);

                    await signInManager.SignInAsync(user, isPersistent : false);

                    return(LocalRedirect(returnUrl));
                }

                // If we cannot find the user email we cannot continue
                ViewBag.ErrorTitle   = $"Email claim not received from: {info.LoginProvider}";
                ViewBag.ErrorMessage = "Please contact support on [email protected]";

                return(View("Error"));
            }
        }
示例#6
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            LoginViewModel model = new LoginViewModel
            {
                ReturnUrl     = returnUrl,
                ExternalLogin = (await signInManager.GetExternalAuthenticationSchemesAsync()).ToList()
            };

            if (remoteError != null)
            {
                ModelState.AddModelError(string.Empty, $"Error from ecternal login provider:{remoteError}");
                return(View("Login", model));
            }
            var info = await signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ModelState.AddModelError(string.Empty, "Error loading external login information");
                return(View("Login", model));
            }

            var             email = info.Principal.FindFirstValue(ClaimTypes.Email);
            ApplicationUser user  = null;

            if (email != null)
            {
                user = await userManager.FindByEmailAsync(email);

                if (user != null && !user.EmailConfirmed)
                {
                    ModelState.AddModelError("", "Email henüz onaylanmadı. Lütfen mailinizi kontrol ediniz.");
                    return(View("Login", model));
                }
            }
            var signInResult = await signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (signInResult.Succeeded)
            {
                return(LocalRedirect(returnUrl));
            }
            else
            {
                if (email != null)
                {
                    if (user == null)
                    {
                        user = new ApplicationUser
                        {
                            UserName = info.Principal.FindFirstValue(ClaimTypes.Email),
                            Email    = info.Principal.FindFirstValue(ClaimTypes.Email)
                        };
                        await userManager.CreateAsync(user);

                        var token            = userManager.GenerateEmailConfirmationTokenAsync(user).Result;
                        var confirmationLink = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, token = token }, Request.Scheme);
                        ViewBag.Title   = "Kayıt başarıyla tamamlandı.";
                        ViewBag.Messaje = "Giriş yapmadan önce lütfen mail adresinizi onaylayınız";
                        ViewBag.Link    = confirmationLink;
                        return(View("_Success"));
                    }
                    await userManager.AddLoginAsync(user, info);

                    await signInManager.SignInAsync(user, isPersistent : false);

                    return(LocalRedirect(returnUrl));
                }
            }
            ViewBag.ErrorTitle = $"E posta talebi alınmadı:{info.LoginProvider}";
            return(View("_Error"));
        }
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            // if returlUrl is null, then redirect to root
            returnUrl = returnUrl ?? Url.Content("~/");

            LoginViewModel loginViewModel = new LoginViewModel
            {
                ReturnUrl      = returnUrl,
                ExternalLogins = (await signInManager.GetExternalAuthenticationSchemesAsync()).ToList()
            };

            if (remoteError != null)
            {
                ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");

                return(View("Login", loginViewModel));
            }

            // Get the login information about the user from the external login provider
            var info = await signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ModelState
                .AddModelError(string.Empty, "Error loading external login information.");

                return(View("Login", loginViewModel));
            }


            // Get the email claim value from enteral provider
            var             email = info.Principal.FindFirstValue(ClaimTypes.Email);
            ApplicationUser user  = null;

            if (email != null)
            {
                // check the email we get from the external provider to see if the email has been confirmed.
                user = await userManager.FindByEmailAsync(email);

                // if the user exist, but email is not confirmed
                if (user != null && !user.EmailConfirmed)
                {
                    ModelState.AddModelError(string.Empty, "Email not confirmed yet");
                    return(View("Login", loginViewModel));
                }
            }

            // the rest of cases:
            // 1. if email is null
            // 2. if email is not null and user not exist and email is not confirmed
            // 3. if email is not null and user exists and email is confirmed

            // If the user already has a login (i.e if there is a record in AspNetUserLogins
            // table) then sign-in the user with this external login provider
            // for external login to work, there must be a corresponding record AspNetUserLogins table.
            var signInResult = await signInManager.ExternalLoginSignInAsync(info.LoginProvider,
                                                                            info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (signInResult.Succeeded)
            {
                return(LocalRedirect(returnUrl));
            }
            // If there is no record in AspNetUserLogins table, the user may not have
            // a local account, then we will create a local account using the email
            else
            {
                if (email != null)
                {
                    // Create a new user without password in our local if we do not have a user already
                    // if we have more than 1 external identity provider like google and facebook,
                    // if they all using same email, then this check will make sure we only create 1 user record in our database
                    // user = await userManager.FindByEmailAsync(email);

                    if (user == null)
                    {
                        user = new ApplicationUser
                        {
                            UserName = info.Principal.FindFirstValue(ClaimTypes.Email),
                            Email    = info.Principal.FindFirstValue(ClaimTypes.Email)
                        };

                        await userManager.CreateAsync(user);

                        // after seccuessul register, we want to generate email confirmation email
                        var token = await userManager.GenerateEmailConfirmationTokenAsync(user);

                        // MUST create `ConfirmEmail` action method first, otherwise Url.Action() will always return null when there /controller/action is invalid
                        var confirmationLink = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, token = token }, Request.Scheme);

                        logger.Log(LogLevel.Warning, confirmationLink);

                        ViewBag.ErrorTitle   = "Registration successful";
                        ViewBag.ErrorMessage = "Before you can Login, please confirm your " +
                                               "email, by clicking on the confirmation link we have emailed you";
                        return(View("Error"));
                    }

                    // Add a login (i.e insert a row for the user in AspNetUserLogins table)
                    await userManager.AddLoginAsync(user, info);

                    await signInManager.SignInAsync(user, isPersistent : false);

                    return(LocalRedirect(returnUrl));
                }

                // If we cannot find the user email we cannot continue
                ViewBag.ErrorTitle   = $"Email claim not received from: {info.LoginProvider}";
                ViewBag.ErrorMessage = "Please contact support on [email protected]";

                return(View("Error"));
            }
        }
示例#8
0
        //tak boleh ada rest method, nanti return error
        public async Task <IActionResult> ExternalLoginCallBack(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            LoginVM model = new LoginVM
            {
                ReturnUrl     = returnUrl,
                ExernalLogins = (await signInManager.GetExternalAuthenticationSchemesAsync()).ToList()
            };

            var userInfoData = await signInManager.GetExternalLoginInfoAsync();

            if (remoteError != null)
            {
                ModelState.AddModelError("", $"Error from external provider:{remoteError}");
                return(View("Login", model));
            }

            if (userInfoData == null)
            {
                ModelState.AddModelError("", $"Error loading external login informationo");
                return(View("Login", model));
            }

            var             email = userInfoData.Principal.FindFirstValue(ClaimTypes.Email);
            ApplicationUser user  = null;

            if (email != null)
            {
                user = await userManager.FindByEmailAsync(email);

                if (user != null && !user.EmailConfirmed)
                {
                    ModelState.AddModelError("", "Email not confirmed yet");
                    return(View("Login", model));
                }
            }

            var signInResult = await signInManager.ExternalLoginSignInAsync
                                   (userInfoData.LoginProvider, userInfoData.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (signInResult.Succeeded)
            {
                return(LocalRedirect(returnUrl));
            }
            else
            {
                //kalau masuk sini maksudnya user takda dalam database
                if (email != null)
                {
                    if (user == null)
                    {
                        user = new ApplicationUser
                        {
                            UserName = userInfoData.Principal.FindFirstValue(ClaimTypes.Email),
                            Email    = userInfoData.Principal.FindFirstValue(ClaimTypes.Email)
                        };

                        await userManager.CreateAsync(user);

                        var token = await userManager.GenerateEmailConfirmationTokenAsync(user);

                        var confirmationLink = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, token = token }, Request.Scheme);

                        logger.Log(LogLevel.Warning, confirmationLink);

                        ViewBag.ErrorTitle   = $"Registration Successful";
                        ViewBag.ErrorMessage = "Before you can login, please confirm your email by clicking on the confirmation link we have emailed you";

                        return(View("~/Views/Error/Error.cshtml"));
                    }

                    await userManager.AddLoginAsync(user, userInfoData);

                    await signInManager.SignInAsync(user, isPersistent : false);

                    return(LocalRedirect(returnUrl));
                }

                ViewBag.ErrorTitle   = $"Email claim not received from: {userInfoData.LoginProvider}";
                ViewBag.ErrorMessage = "Please contact support on [email protected]";

                return(View("~/Views/Error/Error.cshtml"));
            }
        }