Beispiel #1
0
    private void SetUserDataAndRedirect(UserInfo userInfo)
    {
        Session["JobNo"]    = userInfo.JobNo;
        Session["UserName"] = userInfo.RealName;
        Session["UserID"]   = userInfo.UserID;
        Session["RoleID"]   = userInfo.RoleID;
        string userID = userInfo.JobNo;

        // 获得 来到登录页之前的页面,即url中return参数的值
        string url = FormsAuthentication.GetRedirectUrl(userID.ToString(), true);

        Response.Redirect("~/Index.htm");
    }
        /// <summary>
        /// Signs specified user in.
        /// </summary>
        /// <param name="username">The username to sign in.</param>
        /// <returns>The URL to redirect user to.</returns>
        public string SignIn(string username, bool rememberMe)
        {
            FormsAuthentication.SetAuthCookie(username, rememberMe);

            var url = FormsAuthentication.GetRedirectUrl(username, false);

            if (String.IsNullOrEmpty(url) || url == "/")
            {
                url = FormsAuthentication.DefaultUrl;
            }

            return(url);
        }
Beispiel #3
0
        private void HandleLoginSuccess(string userName, bool remember)
        {
            string url = FormsAuthentication.GetRedirectUrl(userName, remember);

            if (url.Equals(FormsAuthentication.DefaultUrl, StringComparison.OrdinalIgnoreCase) ||
                url.Contains(".axd") ||
                url.Contains("/Apps/Core/Controls/Uploader/"))
            {
                url = "~/Apps/Shell/Pages/default.aspx";
            }

            Response.Redirect(url);
        }
Beispiel #4
0
        protected void btnLogon_Click(object sender, EventArgs e)
        {
            // Path to you LDAP directory server.
            // Contact your network administrator to obtain a valid path.
            string adPath =
                "LDAP://172.30.1.227/DC=corp,DC=fetec,DC=dsv,DC=ru";

            LdapAuthentication adAuth = new LdapAuthentication(adPath);

            try
            {
                if (true == adAuth.IsAuthenticated(txtDomainName.Text,
                                                   txtUserName.Text,
                                                   txtPassword.Text))
                {
                    // Retrieve the user's groups
                    string groups = adAuth.GetGroups();
                    // Create the authetication ticket
                    FormsAuthenticationTicket authTicket =
                        new FormsAuthenticationTicket(1,  // version
                                                      txtUserName.Text,
                                                      DateTime.Now,
                                                      DateTime.Now.AddMinutes(60),
                                                      false, groups);
                    // Now encrypt the ticket.
                    string encryptedTicket =
                        FormsAuthentication.Encrypt(authTicket);
                    // Create a cookie and add the encrypted ticket to the
                    // cookie as data.
                    HttpCookie authCookie =
                        new HttpCookie(FormsAuthentication.FormsCookieName,
                                       encryptedTicket);
                    // Add the cookie to the outgoing cookies collection.
                    Response.Cookies.Add(authCookie);

                    // Redirect the user to the originally requested page
                    Response.Redirect(
                        FormsAuthentication.GetRedirectUrl(txtUserName.Text,
                                                           false));
                }
                else
                {
                    lblError.Text =
                        "Authentication failed, check username and password.";
                }
            }
            catch (Exception ex)
            {
                lblError.Text = "Error authenticating. " + ex.Message;
            }
        }
Beispiel #5
0
        public ActionResult Login(AccountLoginViewModel login)
        {
            //Validate a username and password(no empties)
            if (login == null)
            {
                ModelState.AddModelError("", "Login is required.");
                return(View());
            }

            if (string.IsNullOrWhiteSpace(login.Username))
            {
                ModelState.AddModelError("", "Username is required.");
                return(View());
            }

            if (string.IsNullOrWhiteSpace(login.Password))
            {
                ModelState.AddModelError("", "Password is required.");
                return(View());
            }

            bool isValid = false;

            using (wsadDbContext context = new wsadDbContext())
            {
                //hash password

                //Query for the user based on username and password hash
                if (context.Users.Any(
                        row => row.UserName.Equals(login.Username) &&
                        row.Password.Equals(login.Password)
                        ))
                {
                    isValid = true;
                }
            }

            //If invalid, send error
            if (!isValid)
            {
                ModelState.AddModelError("", "Invalid UserName or Password");
                return(View());
            }
            else
            {
                //Valid, redirect to user profile
                System.Web.Security.FormsAuthentication.SetAuthCookie(login.Username, login.RememberMe);

                return(Redirect(FormsAuthentication.GetRedirectUrl(login.Username, login.RememberMe)));
            }
        }
Beispiel #6
0
        public ActionResult Login(string username, string password)
        {
            bool validLogin = DB.Authors_ValidateLogin(username, password).Value;

            if (validLogin)
            {
                var author    = AuthorModel.GetAuthorBySlug(username);
                var principal = new AuthorPrincipal(author);

                var userData    = JsonConvert.SerializeObject(principal.ToSerializableModel());
                var issued      = DateTime.Now;
                var expiresDate = issued.AddMinutes(30);
                var authTicket  = new FormsAuthenticationTicket(1, author.Slug, issued, expiresDate, false, userData);

                string encTicket = FormsAuthentication.Encrypt(authTicket);
                var    cookie    = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
                {
                    HttpOnly = true,
                    Expires  = expiresDate,
                    Path     = FormsAuthentication.FormsCookiePath
                };
                this.Response.Cookies.Add(cookie);

                var expiresLong   = issued.AddYears(2);
                var cookieIsAdmin = new HttpCookie("IS_ADMIN", "1")
                {
                    HttpOnly = false,
                    Expires  = expiresLong,
                    Path     = FormsAuthentication.FormsCookiePath
                };
                this.Response.Cookies.Add(cookieIsAdmin);

                var ticket = new FormsAuthenticationTicket(1, author.Name, issued, expiresLong, true, "author:" + author.Slug);
                this.Response.SetCookie(new HttpCookie("tdwtf_token", FormsAuthentication.Encrypt(ticket))
                {
                    HttpOnly = true,
                    Expires  = expiresLong,
                    Path     = FormsAuthentication.FormsCookiePath
                });
                this.Response.SetCookie(new HttpCookie("tdwtf_token_name", author.Name)
                {
                    HttpOnly = false,
                    Expires  = expiresLong,
                    Path     = FormsAuthentication.FormsCookiePath
                });

                return(new RedirectResult(FormsAuthentication.GetRedirectUrl(author.Slug, false)));
            }

            return(View());
        }
Beispiel #7
0
        protected void Loginbtn_Click(object sender, EventArgs e)
        {
            int       userId = 0;
            string    roles  = string.Empty;
            string    userX  = "";
            string    pass   = dh.RunQueryDirectly("Select * from SystemSettings Where SettingName='ENCRYPTION_KEY'", "SettingValue");
            string    EncPwd = E.EncryptString(password.Text, pass);
            DataTable tbl    = dh.GetData(
                "Validate_User",
                new object[] { email.Text, EncPwd }
                );

            foreach (DataRow reader in tbl.Rows)
            {
                userX  = reader["UserId"].ToString();
                userId = Convert.ToInt32(userX);
                roles  = reader["Roles"].ToString();
            }
            switch (userId)
            {
            case -1:
                msg.Text = "Username and/or password is incorrect.";
                break;

            case -2:
                msg.Text = "Your Account has not been activated.";
                break;

            case 0:
                dh.InsertData("LogAuditTrail", new string[] { "LOG IN", DateTime.Now.ToString(), " USER " + Session["USERIDENTITY"].ToString() + "HAS LOGGED IN " });
                Response.Redirect("account/account");
                break;

            default:
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                    701, email.Text, DateTime.Now, DateTime.Now.AddMinutes(60 * 24 * 2),
                    true, roles, FormsAuthentication.FormsCookiePath
                    );
                string     hash   = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
                Session["CUSTOMERIDENTITY"] = userX;
                Session["CUTOMERROLE"]      = roles;
                if (ticket.IsPersistent)
                {
                    cookie.Expires = ticket.Expiration;
                }
                Response.Cookies.Add(cookie);
                Response.Redirect(FormsAuthentication.GetRedirectUrl(email.Text, true));
                break;
            }
        }
        /// <summary>
        /// Handles Login button-click events.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoginBtn_Click(object sender, System.EventArgs e)
        {
            bool passwordVerified = false;

            try {
                // Verify password and set authorization cookie, if valid.
                passwordVerified =
                    UserAccounts.VerifyPassword(txtUserName.Text, txtPassword.Text);
                UserAccounts.UserInfo user = UserAccounts.getUserInfo(txtUserName.Text);

                if (!passwordVerified)
                {
                    // First, see if the username exists and if the password
                    // is correct.  If the username doesn't exist, or if
                    // the password is incorrect, reset the fields and notify
                    // user of the problem.
                    lblMessage.Text  = "Invalid username or password.";
                    txtUserName.Text = "";
                    txtPassword.Text = "";
                }
                else if (user.Role == UserRole.Disabled)
                {
                    // If the username exists and the password was correct,
                    // check to see if the account has been disabled.  If so,
                    // notify the user and reset the fields.
                    lblMessage.Text  = "That account has been disabled.";
                    txtUserName.Text = "";
                    txtPassword.Text = "";
                }
                else
                {
                    // Keep track of redirection information
                    string url = Request.QueryString["ReturnUrl"] == null ? "MyAccount.aspx" :
                                 FormsAuthentication.GetRedirectUrl(txtUserName.Text, false);

                    if (user.Role == UserRole.Canceled)
                    {
                        // If this account had been Canceled, reset them to User status,
                        // and redirect them to a page with the appropriate information.
                        user.Role = UserRole.User;
                        UsersControl.updateUserRole(user);
                        Session["CancelType"] = "Reactivate";
                        url = "AccountCanceled.aspx?ReturnUrl=" + url;
                    }

                    Response.Redirect(url);
                }
            } catch (Exception ex) {
                lblMessage.Text = ex.Message;
            }
        }
Beispiel #9
0
        public ActionResult Login(LoginUserVM model)
        {
            string LoggedInUser    = Session["LoggedInUser"] as string;
            string CheckoutRequest = Session["CheckoutRequest"] as string;

            // Check model state
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // Check if the user is valid

            bool isValid = false;

            using (Db db = new Db())
            {
                if (db.Users.Any(x => x.Username.Equals(model.Username) && x.Password.Equals(model.Password)))
                {
                    isValid = true;
                }
            }

            if (!isValid)
            {
                ModelState.AddModelError("", "Invalid username or password.");
                return(View(model));
            }
            else
            {
                if (LoggedInUser != "yes")
                {
                    Session["LoggedInUser"] = "******";
                    //Debug.WriteLine("#1" + "---------- Account: Login: LoggedInUser? "
                    //+ Session["LoggedInUser"].ToString());
                }

                if (CheckoutRequest == "yes")
                {
                    Session["CheckoutRequest"] = "no";
                    //Debug.WriteLine("#1" + "---------- Account: Login: LoggedInUser2? "
                    //+ Session["LoggedInUser"].ToString());
                    //Debug.WriteLine("#1" + "---------- Account: Login: CheckoutRequest");
                    FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);
                    return(Redirect("/cart"));
                }

                FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);
                return(Redirect(FormsAuthentication.GetRedirectUrl(model.Username, model.RememberMe)));
            }
        }
Beispiel #10
0
        /// <summary>Evento de click no buto</summary>
        protected void onLoginClick(object src, ImageClickEventArgs args)
        {
            //verificar se as string n esto vazias
            if (userMail.Text == string.Empty)
            {
                Information.AddError(info.getContent("provide-mail"));
                return;
            }

            if (!Regex.IsMatch(userMail.Text, @"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"))
            {
                Information.AddError(info.getContent("bad-mail-format"));
                return;
            }

            if (password.Text == string.Empty)
            {
                Information.AddError(info.getContent("provide-password"));
                return;
            }

            if ((userMail.Text.IndexOf(" ")) == 0 || (password.Text.IndexOf(" ")) == 0)
            {
                Information.AddError(info.getContent("login-error"));
                return;
            }

            bool user = UserUtility.bd.checkUser(userMail.Text, password.Text);

            if (!user)
            {
                Information.AddError(info.getContent("login-error"));
                return;
            }
            login.Visible  = false;
            logout.Visible = true;
            FormsAuthentication.SetAuthCookie(userMail.Text, autoLogin.Checked);
            string redirectUrl = FormsAuthentication.GetRedirectUrl(userMail.Text, autoLogin.Checked).ToLower();

            HttpContext context = HttpContext.Current;

            if (context.Request.QueryString["ReturnUrl"] != null)
            {
                context.Response.Redirect(redirectUrl);
            }
            else
            {
                context.Response.Redirect(OrionGlobals.resolveBase("default.aspx"));
            }
        }
Beispiel #11
0
 public ActionResult Login(string username, string password)
 {
     if (AuthenticationCookieProvider.LogIn(username, password))
     {
         return(Redirect(FormsAuthentication.GetRedirectUrl(username, false)));
     }
     else
     {
         ViewBag.ShowMessage  = true;
         ViewBag.MessageColor = "red";
         ViewBag.Message      = Resources.Resources.LoginFailed;
         return(View());
     }
 }
Beispiel #12
0
        public static void SetAuthenticationTicket(Page page, string userName, bool rememberMe)
        {
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now,
                                                                             DateTime.Now.AddMinutes(30), rememberMe, String.Empty, FormsAuthentication.FormsCookiePath);
            string encryptedCookie = FormsAuthentication.Encrypt(ticket);

            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedCookie);

            cookie.Domain = FormsAuthentication.CookieDomain;
            cookie.Path   = ticket.CookiePath;

            page.Response.Cookies.Add(cookie);
            page.Response.Redirect(FormsAuthentication.GetRedirectUrl(userName, rememberMe));
        }
Beispiel #13
0
        public ActionResult SignIn(string name, string password)
        {
            T_UserInfo userinfo = WazDb.QueryUserInfoByNameAndPassword(name, password);

            if (userinfo == null)
            {
                return(View());
            }
            else
            {
                AuthManager.SignIn(HttpContext, userinfo, 60 * 24 * 90);
                return(Redirect(FormsAuthentication.GetRedirectUrl(userinfo.Name, false)));
            }
        }
 public ActionResult Index(Login request)
 {
     if (!ModelState.IsValid)
     {
         return(View(request));
     }
     if (!string.IsNullOrEmpty(request.Username) && !string.IsNullOrEmpty(request.Password))
     {
         FormsAuthentication.SetAuthCookie(request.Username, false);
         return(Redirect(FormsAuthentication.GetRedirectUrl(request.Username, false)));
     }
     ViewBag.Failed = true;
     return(View(request));
 }
Beispiel #15
0
        private void btnLogin_Click(object sender, System.EventArgs e)
        {
            AuthenticationModule am = (AuthenticationModule)this.Context.ApplicationInstance.Modules["AuthenticationModule"];

            if (am.AuthenticateUser(txtUsername.Text, txtPassword.Text, false))
            {
                Context.Response.Redirect(FormsAuthentication.GetRedirectUrl(this.User.Identity.Name, false));
            }
            else
            {
                this.lblError.Text    = "Invalid username or password.";
                this.lblError.Visible = true;
            }
        }
Beispiel #16
0
        public ActionResult LogIn(string Login, string Senha)
        {
            Session.Clear(); Session.Abandon();
            if (UsuarioBusiness.LogIn(Login, Senha))
            {
                var url = FormsAuthentication.GetRedirectUrl(Login, true);
                FormsAuthentication.SetAuthCookie(Login, true);
                return(Redirect(url));
            }

            TempData["massage"] = "Login e ou Senha incorretos.";

            return(RedirectToAction("Index"));
        }
Beispiel #17
0
    protected void Login_Authenticate(object sender, AuthenticateEventArgs e)
    {
        int    userId = 0;
        string roles  = string.Empty;
        string constr = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;

        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("Validate_User"))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Username", Login.UserName);
                cmd.Parameters.AddWithValue("@Password", Login.Password);
                cmd.Connection = con;
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                reader.Read();
                userId = Convert.ToInt32(reader["UserId"]);
                roles  = reader["Roles"].ToString();
                con.Close();
            }
            switch (userId)
            {
            case -1:
                Login.FailureText = "Username and/or password is incorrect.";
                break;

            case -2:
                Login.FailureText = "Account has not been activated.";
                break;

            default:
                Session["UserId"] = userId;
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, Login.UserName, DateTime.Now, DateTime.Now.AddMinutes(2880), Login.RememberMeSet, roles, FormsAuthentication.FormsCookiePath);
                string     hash   = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);

                if (ticket.IsPersistent)
                {
                    cookie.Expires = ticket.Expiration;
                }
                Response.Cookies.Add(cookie);

                Response.Redirect(FormsAuthentication.GetRedirectUrl(Login.UserName, Login.RememberMeSet));

                break;
            }
        }
    }
Beispiel #18
0
        public ActionResult Login(LoginUserViewModel loginUser)
        {
            //Validate a username and password is passed (no empties)
            if (loginUser == null)
            {
                ModelState.AddModelError("", "Login is required");
                return(View());
            }

            if (string.IsNullOrWhiteSpace(loginUser.Username))
            {
                ModelState.AddModelError("", "Username is required");
                return(View());
            }

            if (string.IsNullOrWhiteSpace(loginUser.Password))
            {
                ModelState.AddModelError("", "Password is required");
                return(View());
            }
            // open database connection
            bool isValid = false;

            using (WSADDbContext context = new WSADDbContext())
            {
                //hash password
                //query for user based on username and password hash
                if (context.Users.Any(
                        row => row.Username.Equals(loginUser.Username) &&
                        row.Password.Equals(loginUser.Password)
                        ))
                {
                    isValid = true;
                }
            }
            //if invalid, send error
            if (!isValid)
            {
                ModelState.AddModelError("", "Invalid username or password.");
                return(View());
            }
            else
            {
                //valid, redirect to user profile

                System.Web.Security.FormsAuthentication.SetAuthCookie(loginUser.Username, loginUser.RememberMe);
                return(Redirect(FormsAuthentication.GetRedirectUrl(loginUser.Username, loginUser.RememberMe)));
            }
        }
Beispiel #19
0
        protected void LoginButton_clicked(object sender, System.EventArgs e)
        {
            string redirectUrl = string.Empty;
            string username    = UserName.Text;
            string password    = Password.Text;



            userRepo = new Repositories.UserRepository();

            if (userRepo.AutheticateUser(username, password))
            {
                string[] userRoles = userRepo.GetRolesAsArray(username);

                HttpCookie AuthorizationCookie = UserHelper.GetAuthorizationCookie(username, userRepo.GetRoles(username));

                HttpContext.Current.User = new GenericPrincipal(User.Identity, userRoles);

                Response.Cookies.Add(AuthorizationCookie);


                Domain.User loggedUser = this.userRepo.GetUserDetails(username);

                loggedUser.Roles.AddRange(userRoles);

                UserHelper.SetLoggedInUser(loggedUser, HttpContext.Current.Session);

                if (HttpContext.Current.User.IsInRole(Helper.Constants.ADMIN_ROLE))
                {
                    redirectUrl = "~/Admin/ManageRegistration.aspx";
                }
                else
                if (HttpContext.Current.User.IsInRole(Helper.Constants.VALIENT_ROLE))
                {
                    redirectUrl = "~/Admin/SelectProvince.aspx";
                }
                else
                {
                    redirectUrl = Constants.GetPortalURLForPhysician(FormsAuthentication.GetRedirectUrl(username, true));
                }


                Response.Redirect(redirectUrl, false);
            }
            else
            {
                lblLoginResult.Text = "Invalid username password";
            }
        }
Beispiel #20
0
        public ActionResult SignIn(SignInViewModel m)
        {
            //未通過Model驗證
            if (!ModelState.IsValid)
            {
                return(View(m));
            }

            //通過Model驗證
            string email    = HttpUtility.HtmlEncode(m.Email);
            string password = HttpUtility.HtmlEncode(m.Password);

            //以Name及Password查詢比對Account資料表記錄
            Member user = db.Member.Where(x => x.m_email == email && x.m_password == password).FirstOrDefault();

            if (user == null)
            {
                ModelState.AddModelError("", "The email or password is invalid.");
                return(View());
            }

            Session["m_name"] = user.m_name.ToString();
            Session["m_id"]   = user.m_id;

            //Create FormsAuthenticationTicket
            var ticket = new FormsAuthenticationTicket(
                version: 1,
                name: user.m_email.ToString(),              //可以放使用者Id
                issueDate: DateTime.UtcNow,                 //現在UTC時間
                expiration: DateTime.UtcNow.AddMinutes(30), //Cookie有效時間=現在時間往後+30分鐘
                isPersistent: true,                         // 是否要記住我 true or false
                userData: "",                               //可以放使用者角色名稱
                cookiePath: FormsAuthentication.FormsCookiePath);

            // Encrypt the ticket.
            var encryptedTicket = FormsAuthentication.Encrypt(ticket); //把驗證的表單加密

            // Create the cookie.
            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

            Response.Cookies.Add(cookie);

            // Redirect back to original URL.
            var url = FormsAuthentication.GetRedirectUrl(email, true);

            //Response.Redirect(FormsAuthentication.GetRedirectUrl(name, true));

            return(RedirectToAction("Index"));
        }
        protected void loginButton_Click(object sender, EventArgs e)
        {
            if (FormsAuthentication.Authenticate(userNameTextBox.Text, passwordTextBox.Text))
            {
                string strRoles = "";
                if (userNameTextBox.Text == "user1")
                {
                    strRoles = "admin,manager";
                }
                else if (userNameTextBox.Text == "user2")
                {
                    strRoles = "admin";
                }
                else if (userNameTextBox.Text == "user4")
                {
                    strRoles = "student,cs";
                }
                else if (userNameTextBox.Text == "user5")
                {
                    strRoles = "staff,cs";
                }
                else
                {
                    strRoles = "";
                }

                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                    1,
                    userNameTextBox.Text,
                    DateTime.Now,
                    DateTime.Now.AddMinutes(30),
                    false,
                    strRoles,
                    FormsAuthentication.FormsCookiePath);

                // Encrypt the ticket.
                string encTicket = FormsAuthentication.Encrypt(ticket);

                // Create the cookie.
                Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

                //Redirect back to original URL.
                Response.Redirect(FormsAuthentication.GetRedirectUrl(userNameTextBox.Text, false));
            }
            else
            {
                errorMessageLabel.Text = "Invalid credentials.";
            }
        }
        protected void btnIdPLogin_Click(object sender, EventArgs e)
        {
            // Get the authentication request.
            AuthnRequest authnRequest = Util.GetAuthnRequest(this);

            // Get SP Resource URL.
            string spResourceUrl = Util.GetAbsoluteUrl(this, FormsAuthentication.GetRedirectUrl("", false));
            // Create relay state.
            string relayState = Guid.NewGuid().ToString();

            // Save the SP Resource URL to the cache.
            SamlSettings.CacheProvider.Insert(relayState, spResourceUrl, new TimeSpan(1, 0, 0));

            switch (Global.SingleSignOnServiceBinding)
            {
            case SamlBinding.HttpRedirect:
                X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.SpCertKey];

                // Send authentication request using HTTP Redirect.
                authnRequest.Redirect(Response, Global.SingleSignOnServiceURL, relayState, x509Certificate.PrivateKey);
                break;

            case SamlBinding.HttpPost:
                // Send authentication request using HTTP POST form.
                authnRequest.SendHttpPost(Response, Global.SingleSignOnServiceURL, relayState);

                // End the response.
                Response.End();
                break;

            case SamlBinding.HttpArtifact:
                // Create a new http artifact.
                string identificationUrl           = Util.GetAbsoluteUrl(this, "~/");
                Saml2ArtifactType0004 httpArtifact = new Saml2ArtifactType0004(SamlArtifact.GetSourceId(identificationUrl), SamlArtifact.GetHandle());

                // Save the authentication request for subsequent sending using the artifact resolution protocol.
                SamlSettings.CacheProvider.Insert(httpArtifact.ToString(), authnRequest.GetXml(), new TimeSpan(1, 0, 0));

                // Send the artifact using HTTP POST form.
                httpArtifact.SendPostForm(Response.OutputStream, Global.SingleSignOnServiceURL, relayState);

                // End the response.
                Response.End();
                break;

            default:
                throw new ApplicationException("Invalid binding type");
            }
        }
Beispiel #23
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            // Path to you LDAP directory server.
            string             adPath = "LDAP://BRDIESMSDC01.lnties.com";
            ldapAuthentication adAuth = new ldapAuthentication(adPath);

            try
            {
                if (true == adAuth.IsAuthenticated(txtDomain.Text,
                                                   txtUser.Text,
                                                   txtPassword.Text))
                {
                    // Retrieve the user's groups
                    string groups = adAuth.GetGroups();
                    // Create the authetication ticket
                    FormsAuthenticationTicket authTicket =
                        new FormsAuthenticationTicket(1,  // version
                                                      txtUser.Text,
                                                      DateTime.Now,
                                                      DateTime.Now.AddMinutes(60),
                                                      false, groups);
                    // Now encrypt the ticket.
                    string encryptedTicket =
                        FormsAuthentication.Encrypt(authTicket);
                    // Create a cookie and add the encrypted ticket to the
                    // cookie as data.
                    HttpCookie authCookie =
                        new HttpCookie(FormsAuthentication.FormsCookieName,
                                       encryptedTicket);
                    // Add the cookie to the outgoing cookies collection.
                    Response.Cookies.Add(authCookie);

                    // Redirect the user to the originally requested page
                    Response.Redirect(
                        FormsAuthentication.GetRedirectUrl(txtUser.Text,
                                                           false));
                    Response.Redirect("LDAP://BRDIESMSDC01.lnties.com");
                }
                else
                {
                    lblError.Text =
                        "User Mismatch, check username and password.";
                }
            }
            catch (Exception ex)
            {
                lblError.Text = "Authentication Fail. " + ex.Message;
            }
        }
Beispiel #24
0
        public ActionResult Login(LoginUserViewModel loginUser)
        {
            //Validate username ans password is passed
            if (loginUser == null)
            {
                ModelState.AddModelError("", "Login is required");
                return(View());
            }
            if (string.IsNullOrWhiteSpace(loginUser.Username))
            {
                ModelState.AddModelError("", "Username is Required");
                return(View());
            }
            if (string.IsNullOrWhiteSpace(loginUser.Password))
            {
                ModelState.AddModelError("", "Password is required");
                return(View());
            }
            //open DB connection
            bool isValid = false;

            using (RateMyLandlordDbContext context = new RateMyLandlordDbContext())
            {
                //Hash password
                string hashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(loginUser.Password, "MD5");

                //query for user based on username and password
                if (context.Users.Any(
                        row => row.Username.Equals(loginUser.Username) &&
                        row.Password.Equals(hashedPassword)
                        ))
                {
                    isValid = true;
                }
            }
            //if invalid send error
            if (!isValid)
            {
                ModelState.AddModelError("", "Invalid Username or Password");
                return(View());
            }
            else
            {
                //valid, redirect to user profile
                System.Web.Security.FormsAuthentication.SetAuthCookie(loginUser.Username, loginUser.RememberMe);

                return(Redirect(FormsAuthentication.GetRedirectUrl(loginUser.Username, loginUser.RememberMe)));
            }
        }
        /// <summary>
        /// Logs in and intializes the session using the given username and password.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="appName"></param>
        /// <param name="redirect"></param>
        public static SessionInfo InitializeSession(string username, string password, string appName, bool redirect)
        {
            using (LoginService service = new LoginService())
            {
                SessionInfo session = service.Login(username, password, appName);
                InitializeSession(session);
                Platform.Log(LogLevel.Info, "[{0}]: {1} has successfully logged in.", appName, username);

                if (redirect)
                {
                    HttpContext.Current.Response.Redirect(FormsAuthentication.GetRedirectUrl(username, false), false);
                }
                return(session);
            }
        }
Beispiel #26
0
 protected void btnLogin_Click(object sender, EventArgs e)
 {
     try
     {
         bool flag = UserUtils.Login(this.UserName.Text.Trim().ToUpper(), this.Password.Text, base.Request.UserHostAddress.ToString());
         if (flag)
         {
             base.Response.Redirect(FormsAuthentication.GetRedirectUrl(this.UserName.Text.Trim().ToUpper(), false), false);
         }
     }
     catch (Exception ex)
     {
         this.litMessage.Text = ex.Message;
     }
 }
Beispiel #27
0
        public ActionResult Index(Models.Login request)
        {
            if (!ModelState.IsValid)
            {
                return(View(request));
            }

            if (!string.IsNullOrEmpty(request.Username) && !string.IsNullOrEmpty(request.Password))
            {
                // cookie will expire after closing browser
                FormsAuthentication.SetAuthCookie(request.Username, false);
                return(Redirect(FormsAuthentication.GetRedirectUrl(request.Username, false)));
            }
            return(View(request));
        }
Beispiel #28
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            VerifyUser check = new VerifyUser();
            int        id    = check.validateUser(user.Value, pwd.Value);

            if (id != 0)
            {
                Session["id"] = id;
                Response.Redirect(FormsAuthentication.GetRedirectUrl(user.Value, false));
            }
            else
            {
                Response.Write("<script>alert('Incorrect Username or Password')</script>");
            }
        }
Beispiel #29
0
        public string WebUserLoginIn(SystemUser systemUser, bool persistentUser, HttpContext context)
        {
            List <SystemRole> listRole = this.systemUserRoleRelationDaoInstance.GetUserAssignRole(systemUser);
            Pair       pair            = new Pair(systemUser, listRole);
            string     userInfo        = SerializableUtil.ConvertObjectToZipedBase64String <Pair>(pair);
            HttpCookie userC           = new HttpCookie(FormsAuthentication.FormsCookieName + "UserInfo", userInfo);

            context.Response.Cookies.Add(userC);
            FormsAuthenticationTicket tk = new FormsAuthenticationTicket(1, systemUser.UserLoginID.ToString(), DateTime.Now, DateTime.Now.AddMinutes(30.0), persistentUser, "", FormsAuthentication.FormsCookiePath);
            string     key = FormsAuthentication.Encrypt(tk);
            HttpCookie ck  = new HttpCookie(FormsAuthentication.FormsCookieName, key);

            context.Response.Cookies.Add(ck);
            return(FormsAuthentication.GetRedirectUrl(systemUser.UserLoginID.ToString(), persistentUser));
        }
Beispiel #30
0
        protected void BtnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                string entity = ((Button)sender).Text;
                if (Page.IsValid)
                {
                    string loginID = Server.HtmlEncode(tb_username.Text.Trim());
                    string pass    = Server.HtmlEncode(tb_password.Text.Trim());

                    if (authenticated(loginID, pass))
                    {
                        //// Create a custom FormsAuthenticationTicket and encrypt it
                        FormsAuthenticationTicket ticket =
                            new FormsAuthenticationTicket(1, _currentUser.loginID,
                                                          System.DateTime.Now,
                                                          System.DateTime.Now.AddMinutes(300),//will expire in 300 min
                                                          false, _currentUser.role,
                                                          FormsAuthentication.FormsCookiePath);

                        // Encrypt the ticket, create the cookie, then redirect.
                        string encTicket = FormsAuthentication.Encrypt(ticket);
                        SetCookie(encTicket);

                        Session["IsIdealRAdmin"] = true;

                        if (ViewState[_returnURL] != null)
                        {
                            Response.Redirect(ViewState[_returnURL].ToString(), false);
                        }
                        else
                        {
                            Response.Redirect(FormsAuthentication.GetRedirectUrl(_currentUser.loginID, false), true);
                        }

                        //Response.Redirect(AllConstStrs.url_home, true);
                    }
                    else
                    {
                        //    ll_msg.CssClass = AllConstStrs.Error_Css;
                        //    ll_msg.Text = AllConstStrs.Login_Fail;
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }