Пример #1
0
        private void ProcessProviderResult()
        {
            // Procesar el resultado de un proveedor de autenticación en la solicitud
            ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect(FormsAuthentication.LoginUrl);
            }

            // Crear la dirección URL de redirección para la comprobación de OpenAuth
            var redirectUrl = "~/Account/RegisterExternalLogin";
            var returnUrl   = Request.QueryString["ReturnUrl"];

            if (!String.IsNullOrEmpty(returnUrl))
            {
                redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
            }

            // Comprobar la carga de OpenAuth
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
            if (!authResult.IsSuccessful)
            {
                Title = "Error de inicio de sesión externo";
                userNameForm.Visible = false;

                providerMessage.Text = String.Format("Error de inicio de sesión externo {0},", ProviderDisplayName);

                // Para ver este error, habilite el seguimiento de página en web.config (<system.web><trace enabled="true"/></system.web>) y visite ~/Trace.axd
                Trace.Warn("OpenAuth", String.Format("Error al comprobar la autenticación con {0})", ProviderDisplayName), authResult.Error);
                return;
            }

            // El usuario ha iniciado sesión con el proveedor correctamente
            // Comprobar si el usuario ya está registrado localmente
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                RedirectToReturnUrl();
            }

            // Almacenar los detalles del proveedor en ViewState
            ProviderName     = authResult.Provider;
            ProviderUserId   = authResult.ProviderUserId;
            ProviderUserName = authResult.UserName;

            // Seccionar la cadena de consulta desde la acción
            Form.Action = ResolveUrl(redirectUrl);

            if (User.Identity.IsAuthenticated)
            {
                // El usuario ya se ha autenticado, agregue el inicio de sesión externo y redirija para volver a la dirección URL
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                RedirectToReturnUrl();
            }
            else
            {
                // El usuario es nuevo, solicitar nombres de pertenencia deseados
                userName.Text = authResult.UserName;
            }
        }
        private void ProcessProviderResult()
        {
            // Process the result from an auth provider in the request
            ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect(FormsAuthentication.LoginUrl);
            }

            // Build the redirect url for OpenAuth verification
            var redirectUrl = "~/Account/RegisterExternalLogin";
            var returnUrl   = Request.QueryString["ReturnUrl"];

            if (!String.IsNullOrEmpty(returnUrl))
            {
                redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
            }

            // Verify the OpenAuth payload
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
            if (!authResult.IsSuccessful)
            {
                Title = "External login failed";
                userNameForm.Visible = false;

                ModelState.AddModelError("Provider", String.Format("External login {0} failed.", ProviderDisplayName));

                // To view this error, enable page tracing in web.config (<system.web><trace enabled="true"/></system.web>) and visit ~/Trace.axd
                Trace.Warn("OpenAuth", String.Format("There was an error verifying authentication with {0})", ProviderDisplayName), authResult.Error);
                return;
            }

            // User has logged in with provider successfully
            // Check if user is already registered locally
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                RedirectToReturnUrl();
            }

            // Store the provider details in ViewState
            ProviderName     = authResult.Provider;
            ProviderUserId   = authResult.ProviderUserId;
            ProviderUserName = authResult.UserName;

            // Strip the query string from action
            Form.Action = ResolveUrl(redirectUrl);

            if (User.Identity.IsAuthenticated)
            {
                // User is already authenticated, add the external login and redirect to return url
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                RedirectToReturnUrl();
            }
            else
            {
                // User is new, ask for their desired membership name
                userName.Text = authResult.UserName;
            }
        }
Пример #3
0
        private void ProcessProviderResult()
        {
            // Обработка результата от поставщика проверки подлинности в запросе
            ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect(FormsAuthentication.LoginUrl);
            }

            // Построение URL-адреса перенаправления для проверки OpenAuth
            var redirectUrl = "~/Account/RegisterExternalLogin";
            var returnUrl   = Request.QueryString["ReturnUrl"];

            if (!String.IsNullOrEmpty(returnUrl))
            {
                redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
            }

            // Проверка данных OpenAuth
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
            if (!authResult.IsSuccessful)
            {
                Title = "Ошибка внешней учетной записи";
                userNameForm.Visible = false;

                ModelState.AddModelError("Provider", String.Format("Ошибка внешней учетной записи {0}.", ProviderDisplayName));

                // Чтобы просмотреть ошибку, включите трассировку страниц в файле web.config (<system.web><trace enabled="true"/></system.web>) и откройте адрес ~/Trace.axd
                Trace.Warn("OpenAuth", String.Format("Ошибка при проверке подлинности через {0})", ProviderDisplayName), authResult.Error);
                return;
            }

            // Пользователь успешно вошел через поставщика
            // Проверка того, не зарегистрирован ли пользователь локально
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                RedirectToReturnUrl();
            }

            // Сохранение сведений о поставщике в ViewState
            ProviderName     = authResult.Provider;
            ProviderUserId   = authResult.ProviderUserId;
            ProviderUserName = authResult.UserName;

            // Извлечь строку запроса из действия
            Form.Action = ResolveUrl(redirectUrl);

            if (User.Identity.IsAuthenticated)
            {
                // Пользователь проверен, добавляем внешнюю учетную запись и переходим на URL-адрес возврата
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                RedirectToReturnUrl();
            }
            else
            {
                // Новый пользователь, запрашиваем желаемое имя участника
                userName.Text = authResult.UserName;
            }
        }
Пример #4
0
        private void ProcessProviderResult()
        {
            // 处理请求中的身份验证提供程序返回的结果
            ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect(FormsAuthentication.LoginUrl);
            }

            // 生成重定向 URL 以进行 OpenAuth 验证
            var redirectUrl = "~/Account/RegisterExternalLogin";
            var returnUrl   = Request.QueryString["ReturnUrl"];

            if (!String.IsNullOrEmpty(returnUrl))
            {
                redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
            }

            // 验证 OpenAuth 负载
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
            if (!authResult.IsSuccessful)
            {
                Title = "外部登录失败";
                userNameForm.Visible = false;

                providerMessage.Text = String.Format("外部登录 {0} 失败,", ProviderDisplayName);

                // 若要查看此错误,请在 web.config 中启用页跟踪(<system.web><trace enabled="true"/></system.web>),然后访问 ~/Trace.axd
                Trace.Warn("OpenAuth", String.Format("使用 {0}) 验证身份验证时出错", ProviderDisplayName), authResult.Error);
                return;
            }

            // 用户已成功地使用提供程序登录
            // 检查用户是否已在本地注册
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                RedirectToReturnUrl();
            }

            // 在 ViewState 中存储提供程序详细信息
            ProviderName     = authResult.Provider;
            ProviderUserId   = authResult.ProviderUserId;
            ProviderUserName = authResult.UserName;

            // 从操作中去除查询字符串
            Form.Action = ResolveUrl(redirectUrl);

            if (User.Identity.IsAuthenticated)
            {
                // 用户已进行身份验证,请添加外部登录并重定向到返回 URL
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                RedirectToReturnUrl();
            }
            else
            {
                // 这是新用户,请要求该用户提供所需的成员名称
                userName.Text = authResult.UserName;
            }
        }
Пример #5
0
        private void ProcessProviderResult()
        {
            // 處理要求中驗證提供者所提供的結果
            ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect(FormsAuthentication.LoginUrl);
            }

            // 建立重新導向 URL 以便進行 OpenAuth 驗證
            var redirectUrl = "~/Account/RegisterExternalLogin";
            var returnUrl   = Request.QueryString["ReturnUrl"];

            if (!String.IsNullOrEmpty(returnUrl))
            {
                redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
            }

            //驗證 OpenAuth 裝載
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
            if (!authResult.IsSuccessful)
            {
                Title = "外部登入失敗";
                userNameForm.Visible = false;

                ModelState.AddModelError("Provider", String.Format("外部登入 {0} 失敗。", ProviderDisplayName));

                // 若要檢視此錯誤,請在 web.config (<system.web><trace enabled="true"/></system.web>) 中啟用頁面追蹤並造訪 ~/Trace.axd
                Trace.Warn("OpenAuth", String.Format("使用 {0}) 確認驗證時發生錯誤", ProviderDisplayName), authResult.Error);
                return;
            }

            // 使用者已成功透過提供者登入
            // 檢查使用者是否已在本機註冊
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                RedirectToReturnUrl();
            }

            // 在 ViewState 中儲存提供者詳細資料
            ProviderName     = authResult.Provider;
            ProviderUserId   = authResult.ProviderUserId;
            ProviderUserName = authResult.UserName;

            // 使查詢字串脫離動作
            Form.Action = ResolveUrl(redirectUrl);

            if (User.Identity.IsAuthenticated)
            {
                // 使用者已經過驗證,新增外部登入並重新導向以傳回 url
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                RedirectToReturnUrl();
            }
            else
            {
                // 使用者是新的,詢問其所需的成員資格名稱
                userName.Text = authResult.UserName;
            }
        }
Пример #6
0
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            string ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (ProviderName == null || ProviderName == "")
            {
                NameValueCollection nvs = Request.QueryString;
                if (nvs.Count > 0)
                {
                    if (nvs["state"] != null)
                    {
                        NameValueCollection provideritem = HttpUtility.ParseQueryString(nvs["state"]);
                        if (provideritem["__provider__"] != null)
                        {
                            ProviderName = provideritem["__provider__"];
                        }
                    }
                }
            }

            GoogleOAuth2Client.RewriteRequest();

            var redirectUrl = Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl });
            var retUrl      = returnUrl;
            var authResult  = OpenAuth.VerifyAuthentication(redirectUrl);


            //string ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);

            if (!authResult.IsSuccessful)
            {
                return(Redirect(Url.Action("Login", "Login")));
            }

            // User has logged in with provider successfully
            // Check if user is already registered locally
            //You can call you user data access method to check and create users based on your model
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                return(Redirect(Url.Action("Index", "Home")));
            }

            //Get provider user details
            string ProviderUserId   = authResult.ProviderUserId;
            string ProviderUserName = authResult.UserName;

            string Email = null;

            if (Email == null && authResult.ExtraData.ContainsKey("email"))
            {
                Email = authResult.ExtraData["email"];
            }

            if (User.Identity.IsAuthenticated)
            {
                // User is already authenticated, add the external login and redirect to return url
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                return(Redirect(Url.Action("Index", "Home")));
            }
            else
            {
                // User is new, save email as username
                string membershipUserName = Email ?? ProviderUserId;
                var    createResult       = OpenAuth.CreateUser(ProviderName, ProviderUserId, ProviderUserName, membershipUserName);

                if (!createResult.IsSuccessful)
                {
                    ViewBag.Message = "User cannot be created";
                    return(View());
                }
                else
                {
                    // User created
                    if (OpenAuth.Login(ProviderName, ProviderUserId, createPersistentCookie: false))
                    {
                        return(Redirect(Url.Action("Index", "Home")));
                    }
                }
            }
            return(View());
        }
Пример #7
0
        private void ProcessProviderResult()
        {
            // Elaborare il risultato fornito da un provider di autenticazione nella richiesta
            ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect(FormsAuthentication.LoginUrl);
            }

            // Generare l'URL di reindirizzamento per la verifica OpenAuth
            var redirectUrl = "~/Account/RegisterExternalLogin";
            var returnUrl   = Request.QueryString["ReturnUrl"];

            if (!String.IsNullOrEmpty(returnUrl))
            {
                redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
            }

            // Verificare il payload OpenAuth
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
            if (!authResult.IsSuccessful)
            {
                Title = "Accesso esterno non riuscito";
                userNameForm.Visible = false;

                ModelState.AddModelError("Provider", String.Format("Accesso esterno {0} non riuscito.", ProviderDisplayName));

                // Per visualizzare questo errore, abilitare la traccia delle pagine in web.config (<system.web><trace enabled="true"/></system.web>) e visitare ~/Trace.axd
                Trace.Warn("OpenAuth", String.Format("Si è verificato un errore durante la verifica dell'autenticazione con {0})", ProviderDisplayName), authResult.Error);
                return;
            }

            // L'utente ha eseguito l'accesso con il provider
            // Verificare se l'utente è già registrato nel computer locale
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                RedirectToReturnUrl();
            }

            // Archiviare i dati del provider in ViewState
            ProviderName     = authResult.Provider;
            ProviderUserId   = authResult.ProviderUserId;
            ProviderUserName = authResult.UserName;

            // Rimuovere la stringa di query dall'azione
            Form.Action = ResolveUrl(redirectUrl);

            if (User.Identity.IsAuthenticated)
            {
                // L'utente è già autenticato, aggiungere l'account di accesso esterno ed eseguire il reindirizzamento all'URL restituito
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                RedirectToReturnUrl();
            }
            else
            {
                // L'utente è nuovo, chiedere di specificare il nome di appartenenza desiderato
                userName.Text = authResult.UserName;
            }
        }
Пример #8
0
    private void ProcessProviderResult()
    {
        // Przetwórz wynik od dostawcy uwierzytelniania w żądaniu
        ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

        if (String.IsNullOrEmpty(ProviderName))
        {
            Response.Redirect(FormsAuthentication.LoginUrl);
        }

        ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);

        // Utwórz adres URL przekierowania na potrzeby weryfikacji OpenAuth
        var redirectUrl = "~/Account/RegisterExternalLogin";
        var returnUrl   = Request.QueryString["ReturnUrl"];

        if (!String.IsNullOrEmpty(returnUrl))
        {
            redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
        }

        // Zweryfikuj ładunek OpenAuth
        var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

        if (!authResult.IsSuccessful)
        {
            Title = "Logowanie zewnętrzne nie powiodło się";
            userNameForm.Visible = false;

            providerMessage.Text = String.Format("Logowanie zewnętrzne {0} nie powiodło się,", ProviderDisplayName);

            // Aby wyświetlić ten błąd, włącz śledzenie stron w pliku web.config (<system.web><trace enabled="true"/></system.web>) i przejdź do pliku ~/Trace.axd
            Trace.Warn("OpenAuth", String.Format("Wystąpił błąd podczas weryfikowania uwierzytelniania za pomocą {0})", ProviderDisplayName), authResult.Error);
            return;
        }

        // Użytkownik pomyślnie zalogował się za pomocą dostawcy
        // Sprawdź, czy użytkownik jest już zarejestrowany lokalnie
        if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
        {
            RedirectToReturnUrl();
        }

        // Przechowuj szczegóły dostawcy we właściwości ViewState
        ProviderName     = authResult.Provider;
        ProviderUserId   = authResult.ProviderUserId;
        ProviderUserName = authResult.UserName;

        // Usuń akcję z ciągu zapytania
        Form.Action = ResolveUrl(redirectUrl);

        if (User.Identity.IsAuthenticated)
        {
            // Użytkownik jest już uwierzytelniony, dodaj logowanie zewnętrzne i przekieruj do zwrotnego adresu URL
            OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
            RedirectToReturnUrl();
        }
        else
        {
            // Użytkownik jest nowy, zapytaj, jaką chce mieć nazwę członkowską
            userName.Text = authResult.UserName;
        }
    }
Пример #9
0
        private void ProcessProviderResult()
        {
            // Process the result from an auth provider in the request
            ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect(FormsAuthentication.LoginUrl);
            }

            // Build the redirect url for OpenAuth verification
            var redirectUrl = "~/Account/RegisterExternalLogin";
            var returnUrl   = Request.QueryString["ReturnUrl"];

            if (!String.IsNullOrEmpty(returnUrl))
            {
                redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
            }


            if (ProviderName == "Google")
            {
                GoogleOAuth2Client.RewriteRequest();
            }

            // Verify the OpenAuth payload
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
            if (!authResult.IsSuccessful)
            {
                Title = "External login failed";
                userNameForm.Visible = false;

                providerMessage.Text = String.Format("External login {0} failed,", ProviderDisplayName);

                // To view this error, enable page tracing in web.config (<system.web><trace enabled="true"/></system.web>) and visit ~/Trace.axd
                Trace.Warn("OpenAuth", String.Format("There was an error verifying authentication with {0})", ProviderDisplayName), authResult.Error);
                return;
            }

            // User has logged in with provider successfully
            // Check if user is already registered locally
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                RedirectToReturnUrl();
            }

            // Store the provider details in ViewState
            ProviderName     = authResult.Provider;
            ProviderUserId   = authResult.ProviderUserId;
            ProviderUserName = authResult.UserName;

            // Strip the query string from action
            Form.Action = ResolveUrl(redirectUrl);

            if (User.Identity.IsAuthenticated)
            {
                // User is already authenticated, add the external login and redirect to return url
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                RedirectToReturnUrl();
            }
            else
            {
                // Check if user registration is enabled
                if (Convert.ToInt32(HostSettingManager.Get(HostSettingNames.UserRegistration)) == (int)UserRegistration.None)
                {
                    Response.Redirect("~/AccessDenied.aspx", true);
                }

                // Try to get the email from the provider
                string emailResult = null;
                authResult.ExtraData.TryGetValue("email", out emailResult);

                // User is new, ask for their desired membership name and email
                userName.Text = authResult.UserName;
                email.Text    = emailResult;
            }
        }
        private void ProcessProviderResult()
        {
            // 要求の認証プロバイダーからの結果を処理します
            ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect(FormsAuthentication.LoginUrl);
            }

            // OpenAuth 検証のリダイレクト URL をバインドします
            var redirectUrl = "~/Account/RegisterExternalLogin";
            var returnUrl   = Request.QueryString["ReturnUrl"];

            if (!String.IsNullOrEmpty(returnUrl))
            {
                redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
            }

            // OpenAuth ペイロードを検証します
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
            if (!authResult.IsSuccessful)
            {
                Title = "外部ログインが失敗しました";
                userNameForm.Visible = false;

                providerMessage.Text = String.Format("外部ログイン {0} が失敗しました、", ProviderDisplayName);

                // このエラーを表示するには、web.config (<system.web><trace enabled="true"/></system.web>) でページ トレースを有効にし、~/Trace.axd にアクセスします
                Trace.Warn("OpenAuth", String.Format("{0} での認証の検証でエラーが発生しました)", ProviderDisplayName), authResult.Error);
                return;
            }

            // ユーザーはプロバイダーを使用して正常にログインしました
            // ユーザーが既にローカルで登録されているかどうかを確認します
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                RedirectToReturnUrl();
            }

            // プロバイダーの詳細情報を ViewState に格納します
            ProviderName     = authResult.Provider;
            ProviderUserId   = authResult.ProviderUserId;
            ProviderUserName = authResult.UserName;

            // アクションからクエリ文字列を削除します
            Form.Action = ResolveUrl(redirectUrl);

            if (User.Identity.IsAuthenticated)
            {
                // ユーザーは既に認証されています、戻り先 URL に外部ログインとリダイレクトを追加します
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                RedirectToReturnUrl();
            }
            else
            {
                // ユーザーは新規ユーザーです、ユーザーが希望するメンバーシップ名をたずねます
                userName.Text = authResult.UserName;
            }
        }
Пример #11
0
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            string ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (ProviderName == null || ProviderName == "")
            {
                NameValueCollection nvs = Request.QueryString;
                if (nvs.Count > 0)
                {
                    if (nvs["state"] != null)
                    {
                        NameValueCollection provideritem = HttpUtility.ParseQueryString(nvs["state"]);
                        if (provideritem["__provider__"] != null)
                        {
                            ProviderName = provideritem["__provider__"];
                        }
                    }
                }
            }

            GoogleOAuth2Client.RewriteRequest();

            var redirectUrl = Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl });
            var retUrl      = returnUrl;
            var authResult  = OpenAuth.VerifyAuthentication(redirectUrl);


            if (!authResult.IsSuccessful)
            {
                ViewBag.Message = "Not A Valid EmailID";
                return(Redirect(Url.Action("Account", "Login")));
            }

            // User has logged in with provider successfully
            // Check if user is already registered locally
            //You can call you user data access method to check and create users based on your model
            VC_LMSEntities d     = new VC_LMSEntities();
            string         email = authResult.ExtraData["email"];
            var            row   = d.UsersTables.Where(x => x.EMAIL == email).FirstOrDefault();

            if (row == null)
            {
                ViewBag.Message = "Email not in Database";
                return(RedirectToAction("Index"));
            }
            else
            {
                var id = row.EMPLOYEE_ID;
                //var manager = d.managers.Where(x => x.manager_emp_id == id).FirstOrDefault();
                //if ( manager!= null&&row.Status=="Active")
                //{

                //    Session["userID"] = row.EMPLOYEE_ID;
                //    Session["userName"] = row.FIRST_NAME;
                //    Session["Name"] = row.EMAIL;
                //    return RedirectToAction("Index", "manager");
                //}
                //else
                {
                    var row1 = d.approvers.Where(x => x.approver_id == row.EMPLOYEE_ID).FirstOrDefault();
                    if (row1 != null && row.Status == "Active")
                    {
                        Session["userID"]   = row.EMPLOYEE_ID;
                        Session["userName"] = row.FIRST_NAME;
                        Session["Name"]     = row.EMAIL;
                        return(RedirectToAction("Index", "Approver"));
                    }
                    else if (row.ROLES == "HR" && row.Status == "Active")
                    {
                        Session["userID"]   = row.EMPLOYEE_ID;
                        Session["userName"] = row.FIRST_NAME;
                        Session["Name"]     = row.EMAIL;
                        return(RedirectToAction("Index", "HR"));
                    }
                    else if (row.ROLES == "Employee" && row.Status == "Active")
                    {
                        Session["userID"]   = row.EMPLOYEE_ID;
                        Session["userName"] = row.FIRST_NAME;
                        Session["Name"]     = row.EMAIL;
                        return(RedirectToAction("Index", "Employee"));
                    }
                    else if (row.ROLES == "Admin" && row.Status == "Active")
                    {
                        Session["userID"]   = row.EMPLOYEE_ID;
                        Session["userName"] = row.FIRST_NAME;
                        Session["Name"]     = row.EMAIL;
                        return(RedirectToAction("Index", "Admin"));
                    }
                }
            }
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                return(Redirect(Url.Action("Index", "Home")));
            }

            //Get provider user details
            string ProviderUserId   = authResult.ProviderUserId;
            string ProviderUserName = authResult.UserName;

            string Email = null;

            if (Email == null && authResult.ExtraData.ContainsKey("email"))
            {
                Email = authResult.ExtraData["email"];
            }

            if (User.Identity.IsAuthenticated)
            {
                // User is already authenticated, add the external login and redirect to return url
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                return(Redirect(Url.Action("Index", "Home")));
            }
            else
            {
                // User is new, save email as username
                string membershipUserName = Email ?? ProviderUserId;
                var    createResult       = OpenAuth.CreateUser(ProviderName, ProviderUserId, ProviderUserName, membershipUserName);

                if (!createResult.IsSuccessful)
                {
                    ViewBag.Message = "User cannot be created";
                    return(View());
                }
                else
                {
                    // User created
                    if (OpenAuth.Login(ProviderName, ProviderUserId, createPersistentCookie: false))
                    {
                        return(Redirect(Url.Action("Index", "Home")));
                    }
                }
            }
            return(View());
        }
Пример #12
0
        private void ProcessProviderResult()
        {
            // Traiter le résultat à partir d'un fournisseur d'authentification de la demande
            ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect(FormsAuthentication.LoginUrl);
            }

            // Générer l'URL de redirection pour la vérification OpenAuth
            var redirectUrl = "~/Account/RegisterExternalLogin";
            var returnUrl   = Request.QueryString["ReturnUrl"];

            if (!String.IsNullOrEmpty(returnUrl))
            {
                redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
            }

            // Vérifier la charge utile OpenAuth
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
            if (!authResult.IsSuccessful)
            {
                Title = "Échec de la connexion externe";
                userNameForm.Visible = false;

                ModelState.AddModelError("Provider", String.Format("Échec de la connexion externe {0}.", ProviderDisplayName));

                // Pour afficher cette erreur, activer le traçage des pages dans web.config (<system.web><trace enabled="true"/></system.web>) et consulter ~/Trace.axd
                Trace.Warn("OpenAuth", String.Format("Une erreur est survenue lors de la vérification de l'authentification avec {0})", ProviderDisplayName), authResult.Error);
                return;
            }

            // L'utilisateur s'est bien connecté au fournisseur
            // Vérifier si l'utilisateur est déjà inscrit localement
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                RedirectToReturnUrl();
            }

            // Stocker les détails du fournisseur dans ViewState
            ProviderName     = authResult.Provider;
            ProviderUserId   = authResult.ProviderUserId;
            ProviderUserName = authResult.UserName;

            // Enlever la chaîne de requête de l'action
            Form.Action = ResolveUrl(redirectUrl);

            if (User.Identity.IsAuthenticated)
            {
                // L'utilisateur est déjà authentifié, ajouter la connexion externe et rediriger vers l'URL de renvoi
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                RedirectToReturnUrl();
            }
            else
            {
                // Il s'agit d'un nouvel utilisateur, demander quel est le nom de membre souhaité
                userName.Text = authResult.UserName;
            }
        }
Пример #13
0
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            string ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (ProviderName == null || ProviderName == "")
            {
                NameValueCollection nvs = Request.QueryString;
                if (nvs.Count > 0)
                {
                    if (nvs["state"] != null)
                    {
                        NameValueCollection provideritem = HttpUtility.ParseQueryString(nvs["state"]);
                        if (provideritem["microsoft"] != null)
                        {
                            ProviderName = provideritem["microsoft"];
                        }
                    }
                }
            }

            var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }, this.Request.Url.Scheme);

            if (ProviderName == null)
            {
                ProviderName = "microsoft";
            }

            MicrosoftClient msClient   = OpenAuth.AuthenticationClients.GetByProviderName(ProviderName) as MicrosoftClient;
            var             authResult = msClient.VerifyAuthentication(new HttpContextWrapper(HttpContext.ApplicationInstance.Context), new Uri(redirectUrl));

            if (!authResult.IsSuccessful)
            {
                return(Redirect(Url.Action("Login", "Account")));
            }

            // User has logged in with provider successfully
            // Check if user is already registered locally
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                return(Redirect(Url.Action("Index", "Home")));
            }
            //Get provider user details
            string ProviderUserId   = authResult.ProviderUserId;
            string ProviderUserName = authResult.UserName;
            string FirstName        = null;
            string LastName         = null;

            string Email = null;

            if (FirstName == null && authResult.ExtraData.ContainsKey("firstname"))
            {
                FirstName = authResult.ExtraData["firstname"];
            }
            if (LastName == null && authResult.ExtraData.ContainsKey("lastname"))
            {
                LastName = authResult.ExtraData["lastname"];
            }
            // call extension method to get email
            ExtendedMicrosoftClientUserData data = msClient.GetExtraData(authResult.ExtraData["accesstoken"]);

            Email = data.Emails.Preferred;

            if (User.Identity.IsAuthenticated)
            {
                // User is already authenticated, add the external login and redirect to return url
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                return(Redirect(Url.Action("Index", "Home")));
            }
            else
            {
                // User is new, save email as username
                string membershipUserName = Email ?? ProviderUserId;
                var    createResult       = OpenAuth.CreateUser(ProviderName, ProviderUserId, ProviderUserName, membershipUserName);

                if (!createResult.IsSuccessful)
                {
                    ViewBag.Message = "User cannot be created";
                    return(View());
                }
                else
                {
                    // User created
                    if (OpenAuth.Login(ProviderName, ProviderUserId, createPersistentCookie: false))
                    {
                        return(Redirect(Url.Action("Index", "Home")));
                    }
                }
            }
            return(View());
        }